// app.jsx — router + stato globale + persistenza di sessione + gate
// (versione evoluta dello script inline del prototipo)

const ROUTES = ['gate', 'lettera', 'chi-sei', 'da-chi', 'messaggio', 'regalo', 'grazie'];
const PAGE_COMPONENT = {
  'gate':      window.GatePage,
  'lettera':   window.LetteraPage,
  'chi-sei':   window.ChiSeiPage,
  'da-chi':    window.DaChiPage,
  'messaggio': window.MessaggioPage,
  'regalo':    window.RegaloPage,
  'grazie':    window.GraziePage,
};

function readHash() {
  const h = (location.hash || '').replace(/^#\/?/, '');
  return ROUTES.includes(h) ? h : 'gate';
}

const DEFAULT_STATE = {
  name: '',
  email: '',           // non più raccolto (login Google rimosso)
  loginMethod: null,   // 'manual'
  kind: null,          // 'solo' | 'group'
  groupNames: [''],
  world: '',
  advice: '',
  direction: null,
  method: null,
  amount: '',
};

function App() {
  const [route, setRoute] = React.useState(readHash);

  // Stato iniziale: ripreso dalla sessione se l'utente aveva già compilato
  const [state, setStateRaw] = React.useState(() => ({
    ...DEFAULT_STATE,
    ...(window.Api.loadState() || {}),
  }));

  const setState = React.useCallback(
    (patch) => setStateRaw(s => ({ ...s, ...patch })),
    []
  );

  // Niente perdita di dati al refresh: ogni modifica viene salvata in sessione
  React.useEffect(() => { window.Api.saveState(state); }, [state]);

  // Sincronizza la rotta con l'hash dell'URL
  React.useEffect(() => {
    function onHash() {
      setRoute(readHash());
      window.scrollTo({ top: 0, behavior: 'instant' });
    }
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // Gate: se non hai inserito la password, qualsiasi rotta riporta all'ingresso
  React.useEffect(() => {
    if (route !== 'gate' && !window.Api.isUnlocked()) {
      location.hash = '#/gate';
    }
  }, [route]);

  function go(target) {
    if (!ROUTES.includes(target)) return;
    location.hash = '#/' + target;
  }

  const safeRoute = (route !== 'gate' && !window.Api.isUnlocked()) ? 'gate' : route;
  const Component = PAGE_COMPONENT[safeRoute];

  return (
    <div key={safeRoute} className="page-anim" data-screen-label={safeRoute}>
      <Component go={go} state={state} setState={setState} />
    </div>
  );
}

function whenReady() {
  if (
    window.T && window.Page && window.PrimaryButton &&
    window.FamilyScene && window.DachshundParade &&
    window.GatePage && window.LetteraPage && window.ChiSeiPage &&
    window.DaChiPage && window.MessaggioPage && window.RegaloPage && window.GraziePage &&
    window.Api
  ) {
    ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  } else {
    setTimeout(whenReady, 30);
  }
}
whenReady();
