/* YeYe Portal — Modals + App root */

/* ---------- Service purchase modal ---------- */
function ServiceModal({ service, onClose }) {
  const { t } = useT();
  const s = service || window.YEYE.services[0];
  const icon = window.YEYE.catIcon[s.cat];
  const price = s.p + (s.u || '');
  return (
    <Modal icon={icon} title={t('svc.' + s.k)} sub={t('scat.' + s.cat) + ' · ' + price} onClose={onClose}
      footer={<><Btn variant="ghost" onClick={onClose}>{t('c.cancel')}</Btn><Btn variant="primary" icon="check" onClick={onClose}>{t('mod.confirmAdd')}</Btn></>}>
      <div className="flex col gap-10">
        {['mod.b1', 'mod.b2', 'mod.b3'].map((bk, i) => (
          <div key={i} className="flex ac gap-10"><div className="hd-ic" style={{ width: 28, height: 28, borderRadius: 8 }}><Icon name="check" size={15} /></div><span style={{ fontSize: 13.5 }}>{t(bk)}</span></div>
        ))}
      </div>
      <div className="alert info mt-20"><div className="a-ic"><Icon name="info" size={16} /></div><div className="grow"><div className="a-t">{t('mod.noCharge')}</div><div className="a-s">{t('mod.noChargeDesc')}</div></div></div>
    </Modal>
  );
}

/* ---------- Upload modal ---------- */
function UploadModal({ onClose }) {
  const { t } = useT();
  const [drag, setDrag] = useState(false);
  return (
    <Modal icon="upload" title={t('mod.upTitle')} sub={t('mod.upSub')} onClose={onClose}
      footer={<><Btn variant="ghost" onClick={onClose}>{t('c.cancel')}</Btn><Btn variant="primary" icon="upload" onClick={onClose}>{t('mod.uploadFile')}</Btn></>}>
      <Field label={t('mod.docType')}>
        <select className="select"><option>{t('doc.criminal')}</option><option>{t('doc.insurance')}</option><option>{t('doc.accommodation')}</option><option>{t('mod.normal')}</option></select>
      </Field>
      <div className="mt-16" onDragOver={(e) => { e.preventDefault(); setDrag(true); }} onDragLeave={() => setDrag(false)} onDrop={(e) => { e.preventDefault(); setDrag(false); }}
        style={{ border: '2px dashed ' + (drag ? 'var(--brand-400)' : 'var(--line)'), background: drag ? 'var(--brand-50)' : 'var(--surface-2)', borderRadius: 'var(--r-lg)', padding: '34px 20px', textAlign: 'center', transition: '.15s' }}>
        <div className="hd-ic" style={{ width: 48, height: 48, margin: '0 auto 12px', borderRadius: 13 }}><Icon name="cloud-upload" size={24} /></div>
        <div className="strong">{t('mod.dragTitle')}</div>
        <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>{t('mod.or')} <span style={{ color: 'var(--brand-600)', fontWeight: 600 }}>{t('c.browse')}</span></div>
      </div>
    </Modal>
  );
}

/* ---------- New ticket modal ---------- */
function TicketModal({ onClose }) {
  const { t } = useT();
  return (
    <Modal icon="life-buoy" title={t('mod.ticketTitle')} onClose={onClose}
      footer={<><Btn variant="ghost" onClick={onClose}>{t('c.cancel')}</Btn><Btn variant="primary" icon="send" onClick={onClose}>{t('mod.submit')}</Btn></>}>
      <div className="flex col gap-14">
        <Field label={t('col.category')}><select className="select"><option>{t('cat.immigration')}</option><option>{t('cat.billing')}</option><option>{t('cat.documents')}</option></select></Field>
        <Field label={t('mod.subject')}><input className="input" placeholder={t('mod.subjectPh')} /></Field>
        <Field label={t('mod.detailsL')}><textarea className="ta" placeholder={t('mod.detailsPh')} /></Field>
        <Field label={t('mod.priority')}><div className="flex gap-8"><span className="chip on">{t('mod.normal')}</span><span className="chip">{t('mod.high')}</span><span className="chip">{t('mod.urgent')}</span></div></Field>
      </div>
    </Modal>
  );
}

/* ---------- Notifications panel ---------- */
function NotifPanel({ onClose, go }) {
  const { t } = useT();
  const items = [
    { ic: 'file-warning', ty: 'bad', tk: 'n_criminal', s: '2h' },
    { ic: 'calendar-clock', ty: 'warn', tk: 'n_biometrics', s: '5h' },
    { ic: 'check', ty: 'ok', tk: 'n_verified', s: '1d' },
    { ic: 'megaphone', ty: 'info', tk: 'n_rules', s: '2d' },
    { ic: 'receipt', ty: 'warn', tk: 'n_invoice', s: '3d' },
  ];
  const col = { bad: 'var(--bad)', warn: 'var(--warn)', ok: 'var(--ok)', info: 'var(--info)' };
  const bg = { bad: 'var(--bad-bg)', warn: 'var(--warn-bg)', ok: 'var(--ok-bg)', info: 'var(--info-bg)' };
  return (
    <Panel title={t('sec.notifications')} onClose={onClose} footer={<Btn variant="ghost" className="btn-block" onClick={onClose}>{t('c.markRead')}</Btn>}>
      <div className="rowlist" style={{ margin: '-6px 0' }}>
        {items.map((n, i) => (
          <div key={i} className="lrow pointer" onClick={() => { onClose(); go('dashboard'); }}>
            <div className="l-ic" style={{ background: bg[n.ty], color: col[n.ty] }}><Icon name={n.ic} size={18} /></div>
            <div className="l-bd"><div className="l-t" style={{ fontSize: 13, fontWeight: 500 }}>{t(n.tk)}</div><div className="l-s">{n.s} {t('col.ago')}</div></div>
          </div>
        ))}
      </div>
    </Panel>
  );
}

/* ============================================================
   APP ROOT
   ============================================================ */
const TITLES = {
  dashboard: ['Dashboard', null], services: ['Services Marketplace', 'Purchase & manage services'],
  cases: ['Cases', null], documents: ['Documents', null], appointments: ['Appointments', null],
  messages: ['Messages', null], tasks: ['Tasks', null], invoices: ['Invoices & Billing', null],
  reports: ['Reports', null], support: ['Support Center', null], profile: ['Profile', null], settings: ['Settings', null],
};

function App() {
  const [authState, setAuthState] = useState(() => window.YEYE_AUTH.getState());
  useEffect(() => window.YEYE_AUTH.subscribe(setAuthState), []);
  const [clientType, setClientType] = useState('employee_card');
  const [branding, setBranding] = useState('individual');
  const [page, setPage] = useState('dashboard');
  const [mini, setMini] = useState(false);
  const [drawer, setDrawer] = useState(false);
  const [modal, setModal] = useState(null);
  const [modalData, setModalData] = useState(null);
  const [notif, setNotif] = useState(false);
  const [lang, setLang] = useState(() => localStorage.getItem('yeye-lang') || 'en');
  const authed = !!(authState.user && authState.token && authState.contact);
  const checking = !!authState.gateChecking;

  const t = React.useMemo(() => ((k) => (window.I18N[lang] && window.I18N[lang][k]) || window.I18N.en[k] || k), [lang]);
  const dict = window.I18N[lang] || window.I18N.en;
  const setLangP = (l) => { setLang(l); localStorage.setItem('yeye-lang', l); };

  // Derive case type from GHL tags (falls back to employee_card)
  const deriveCaseType = (tags) => {
    const ts = (tags || []).map((x) => String(x).toLowerCase());
    if (ts.some((x) => x.startsWith('blue_card') || x.includes('bluecard'))) return 'blue_card';
    if (ts.some((x) => x.startsWith('family'))) return 'family_reunion';
    if (ts.some((x) => x.startsWith('business'))) return 'business_visa';
    if (ts.some((x) => x.startsWith('osvc'))) return 'osvc';
    if (ts.some((x) => x.startsWith('relocation'))) return 'relocation';
    if (ts.some((x) => x.startsWith('employee_card') || x.includes('employee_onboarding'))) return 'employee_card';
    return 'employee_card';
  };

  // Build live case-type data from GHL contact + mock template
  const buildLiveCt = (mockCt, contact) => {
    if (!contact) return mockCt;
    const cap = (w) => w ? w.charAt(0).toUpperCase() + w.slice(1) : '';
    const full = [contact.firstName, contact.lastName].filter(Boolean).join(' ').split(' ').map(cap).join(' ').trim();
    const addrField = (contact.customFields || []).find((f) => /correspondence|address|adres/i.test(f.key || ''));
    let region = mockCt.region;
    if (addrField && typeof addrField.value === 'string') {
      const m = addrField.value.match(/([A-Za-zÀ-ž\s]+)\/([A-Za-zÀ-ž\s]+)\s*$/);
      if (m) region = cap(m[1].trim()) + ', ' + cap(m[2].trim());
    }
    const caseId = 'YE-' + String(contact.contactId || '').slice(0, 8).toUpperCase();
    return { ...mockCt, who: full || mockCt.who, region, caseId };
  };

  // Live client-type derived from contact tags; user can still switch via the demo ClientTypeMenu
  const derivedKey = authState.contact ? deriveCaseType(authState.contact.tags) : clientType;
  const effectiveKey = clientType === 'employee_card' && authState.contact ? derivedKey : clientType;
  const mockCt = window.YEYE.clientTypes[effectiveKey] || window.YEYE.clientTypes.employee_card;
  const ctData = buildLiveCt(mockCt, authState.contact);

  const go = (k) => { if (k === 'logout') { window.YEYE_AUTH.signOut(); return; } setPage(k); window.scrollTo && window.scrollTo(0, 0); const c = document.querySelector('.content'); if (c) c.scrollTop = 0; };
  const openModal = (kind, data) => { setModalData(data || null); setModal(kind); };

  // when client type changes, jump to dashboard; employer-sponsored branding only valid for sponsored types
  useEffect(() => { setPage('dashboard'); if (!ctData.org && branding === 'corporate') setBranding('individual'); }, [clientType]);

  // when contact loads, sync clientType to derived
  useEffect(() => {
    if (authState.contact) {
      const k = deriveCaseType(authState.contact.tags);
      if (k !== clientType) setClientType(k);
    }
  }, [authState.contact]);

  const renderPage = () => {
    if (page === 'dashboard') return <ExpatDashboard ct={ctData} go={go} openModal={openModal} />;
    switch (page) {
      case 'services': return <ServicesPage openModal={openModal} />;
      case 'documents': return <DocumentsPage openModal={openModal} />;
      case 'invoices': return <InvoicesPage openModal={openModal} />;
      case 'support': return <SupportPage openModal={openModal} />;
      case 'cases': return <CasesPage />;
      case 'appointments': return <AppointmentsPage />;
      case 'tasks': return <TasksPage />;
      case 'reports': return <ReportsPage />;
      case 'profile': return <SimplePage icon="user" title={t('nav.profile')} sub={t('pg.profileSub')} />;
      case 'settings': return <SimplePage icon="settings" title={t('nav.settings')} sub={t('pg.settingsSub')} />;
      default: return <SimplePage icon="circle-dashed" title={t('pg.soon')} sub={t('pg.soonSub')} />;
    }
  };

  if (!authed) {
    return (
      <LangCtx.Provider value={{ lang, t, dict }}>
        <LoginScreen error={authState.error} checking={checking} />
      </LangCtx.Provider>
    );
  }

  return (
    <LangCtx.Provider value={{ lang, t, dict }}>
    <div className="app">
      <div className={'scrim ' + (drawer ? 'show' : '')} onClick={() => setDrawer(false)} />
      <Sidebar nav={window.YEYE.nav} active={page} onNav={go} mini={mini} open={drawer} onClose={() => setDrawer(false)} ct={ctData} />
      <div className="main">
        <Topbar
          title={page === 'dashboard' ? t('nav.dashboard') : t('nav.' + page)} sub={page === 'dashboard' ? t('ct.' + clientType) : null}
          ct={ctData} branding={branding} onBranding={setBranding}
          ctKey={clientType} onCt={setClientType} lang={lang} onLang={setLangP}
          onToggleSidebar={() => setMini((m) => !m)} onHamburger={() => setDrawer(true)}
          onNotif={() => setNotif(true)} onSearch={() => {}} />
        <div className="content">
          <div className="page">{renderPage()}</div>
          <MobileClientType ctKey={clientType} onCt={setClientType} />
        </div>
      </div>

      {modal === 'service' && <ServiceModal service={modalData} onClose={() => setModal(null)} />}
      {modal === 'upload' && <UploadModal onClose={() => setModal(null)} />}
      {modal === 'ticket' && <TicketModal onClose={() => setModal(null)} />}
      {notif && <NotifPanel onClose={() => setNotif(false)} go={go} />}
    </div>
    </LangCtx.Provider>
  );
}

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