const { useState, createContext, useContext, useEffect } = React;

const AppContext = createContext({});
window.useApp = () => useContext(AppContext);

function Setup() {
  const { t, updateProfile } = window.useApp();
  const [form, setForm] = useState({ companyName: '', address: '', evtc: '', siret: '', defaultPlate: '' });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleStart = () => {
    if (!form.companyName.trim()) return;
    updateProfile(form);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-start', minHeight: '100%', padding: '48px 24px 40px', gap: 24, background: 'var(--bg)' }}>
      <div style={{ width: 64, height: 64, borderRadius: 18, background: 'var(--dark)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <span style={{ fontSize: 28 }}>🚗</span>
      </div>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontSize: 26, fontWeight: 800, color: 'var(--text)', letterSpacing: '-0.5px' }}>{t('setupTitle')}</div>
        <div style={{ fontSize: 15, color: 'var(--text-2)', marginTop: 8, lineHeight: 1.5, maxWidth: 300 }}>{t('setupHint')}</div>
      </div>
      <div style={{ width: '100%', maxWidth: 400, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {[
          { k: 'companyName', label: 'Nom / Raison sociale *', ph: 'Durairaj Ramalingam' },
          { k: 'address', label: 'Adresse du siège social', ph: '12 av. Victor Hugo, 75016 Paris' },
          { k: 'evtc', label: 'Numéro EVTC', ph: '2024/75/1234' },
          { k: 'siret', label: 'SIREN / SIRET', ph: '890 123 456 00017' },
          { k: 'defaultPlate', label: 'Immatriculation par défaut', ph: 'AB-123-CD' },
        ].map(({ k, label, ph }) => (
          <div key={k}>
            <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-2)', marginBottom: 4 }}>{label}</label>
            <input
              style={{ width: '100%', padding: '11px 13px', fontSize: 15, fontFamily: 'var(--font)', color: 'var(--text)', background: 'var(--surface)', border: '1.5px solid var(--border)', borderRadius: 'var(--radius-sm)', outline: 'none', boxSizing: 'border-box' }}
              placeholder={ph} value={form[k]} onChange={e => set(k, e.target.value)}
            />
          </div>
        ))}
        <button
          style={{ marginTop: 8, background: 'var(--dark)', color: '#fff', border: 'none', borderRadius: 'var(--radius)', padding: '14px', fontSize: 16, fontWeight: 700, fontFamily: 'var(--font)', cursor: 'pointer' }}
          onClick={handleStart}
        >{t('setupCta')} →</button>
      </div>
    </div>
  );
}

function App() {
  const [lang, setLang] = useState(() => storage.getLang());
  const [profile, setProfile] = useState(() => storage.getProfile());
  const [bons, setBons] = useState(() => storage.getBons());
  const [screen, setScreen] = useState('home');
  const [navParams, setNavParams] = useState(null);

  const t = (key) => (TRANSLATIONS[lang] || TRANSLATIONS.fr)[key] || key;

  const navigate = (s, params = null) => {
    setScreen(s);
    setNavParams(params);
    window.scrollTo(0, 0);
  };

  const updateProfile = (p) => {
    storage.saveProfile(p);
    setProfile({ ...p });
  };

  const refreshBons = () => setBons(storage.getBons());

  const setLangFn = (l) => {
    storage.setLang(l);
    setLang(l);
  };

  const ctx = { screen, navigate, navParams, t, lang, setLang: setLangFn, profile, updateProfile, bons, refreshBons };

  const showSetup = !profile?.companyName;

  const renderScreen = () => {
    if (showSetup) return (
    <div style={{ height: '100%', overflowY: 'auto' }}>
      <Setup />
    </div>
  );
    switch (screen) {
      case 'home':    return <Dashboard />;
      case 'history': return <History />;
      case 'profile': return <Profile />;
      case 'new':     return <NewBon />;
      case 'preview': return <BonPreview />;
      default:        return <Dashboard />;
    }
  };

  const showNav = !showSetup && !['new', 'preview'].includes(screen);

  return (
    <AppContext.Provider value={ctx}>
      <div style={{ height: '100dvh', display: 'flex', flexDirection: 'column', fontFamily: 'var(--font)', overflow: 'hidden' }}>
        <div style={{ flex: 1, overflow: 'hidden', position: 'relative' }}>
          {renderScreen()}
        </div>
        {showNav && <BottomNav />}
      </div>
    </AppContext.Provider>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
