/* AIWine CRM — app shell: login, sidebar, topbar, hash router */
const { Ic, Badge, Seg, useStore, toast } = window.UI;

/* ---------- routing ---------- */
function useRoute() {
  const parse = () => {
    const h = (location.hash || '#/dashboard').replace(/^#\//, '');
    const [page, id] = h.split('/');
    return { page: page || 'dashboard', id: id || null };
  };
  const [route, setRoute] = React.useState(parse);
  React.useEffect(() => {
    const fn = () => setRoute(parse());
    window.addEventListener('hashchange', fn);
    return () => window.removeEventListener('hashchange', fn);
  }, []);
  return route;
}
window.go = (page, id) => { location.hash = '#/' + page + (id ? '/' + id : ''); window.scrollTo(0, 0); };

/* ---------- login ---------- */
function Login() {
  const store = useStore();
  const [email, setEmail] = React.useState(store.mode === 'demo' ? 'admin@aiwine.co.nz' : '');
  const [pw, setPw] = React.useState('');
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault(); setErr(''); setBusy(true);
    try { await store.signIn(email.trim(), pw); }
    catch (ex) { setErr(ex.message); }
    setBusy(false);
  };

  return (
    <div className="login">
      <div className="login-hero">
        <div>
          <div className="side-wordmark" style={{ fontSize: 24 }}>AI<span className="dot"></span>Wine<span className="suffix">CRM</span></div>
        </div>
        <div>
          <div className="label" style={{ color: 'var(--brass-soft)', marginBottom: 14 }}>Operations platform · NZ + AU</div>
          <h1 className="serif" style={{ fontSize: 46, fontWeight: 500, lineHeight: 1.08, margin: 0 }}>
            Every winery, member<br />and bottle — <em style={{ color: 'var(--brass-soft)' }}>one cellar book.</em>
          </h1>
          <p style={{ color: 'rgba(244,239,229,0.75)', maxWidth: 420, fontSize: 14.5, marginTop: 16 }}>
            Wineries, contacts, consumers, campaigns, memberships, catalogue and support for
            aiwine.co.nz and aiwine.com.au — all reading from the same database.
          </p>
        </div>
        <div className="label" style={{ color: 'rgba(244,239,229,0.5)' }}>Wairarapa, Aotearoa · est. 2026</div>
      </div>
      <div className="login-form">
        <form onSubmit={submit} style={{ width: 'min(360px, 100%)', display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <div className="label" style={{ marginBottom: 8 }}>Sign in</div>
            <h2 className="serif" style={{ margin: 0, fontSize: 30, fontWeight: 500 }}>Welcome back.</h2>
          </div>
          <window.UI.Field label="Email"><input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} autoFocus /></window.UI.Field>
          <window.UI.Field label="Password"><input className="input" type="password" value={pw} onChange={(e) => setPw(e.target.value)} /></window.UI.Field>
          {err && <div style={{ color: 'var(--claret)', fontSize: 12.5, fontWeight: 600 }}>{err}</div>}
          <button className="btn btn-primary" type="submit" disabled={busy} style={{ justifyContent: 'center' }}>{busy ? 'Signing in…' : 'Sign in'}</button>
          {store.mode === 'demo' && (
            <div className="card card-pad" style={{ fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.6 }}>
              <span className="badge badge-brass" style={{ marginBottom: 8 }}>{(store.cache.settings || {}).dataset === 'real' ? 'Real data · this browser only' : 'Demo mode'}</span>
              {(store.cache.settings || {}).dataset === 'real'
                ? <div>Running on your real NZ winery list — stored in this browser until Supabase is connected (see DEPLOYMENT.md). Export a backup before clearing browser data.</div>
                : <div>Running on sample data in your browser — no database connected yet.</div>}
              <div style={{ marginTop: 6 }}>Sign in with <b className="mono" style={{ fontSize: 11.5 }}>admin@aiwine.co.nz</b> / <b className="mono" style={{ fontSize: 11.5 }}>aiwine</b></div>
            </div>
          )}
        </form>
      </div>
    </div>
  );
}

/* ---------- sidebar ---------- */
const NAV = [
  { section: 'Overview', items: [
    { id: 'dashboard', label: 'Dashboard', icon: 'home' },
    { id: 'tasks', label: 'Tasks', icon: 'task', count: (s) => s.t('tasks').filter((t) => !t.done && new Date(t.due) <= new Date(Date.now() + 86400000)).length },
  ]},
  { section: 'Relationships', items: [
    { id: 'wineries', label: 'Wineries', icon: 'winery', count: (s) => s.t('wineries').length },
    { id: 'contacts', label: 'Contacts', icon: 'users' },
    { id: 'consumers', label: 'Consumers', icon: 'consumer' },
  ]},
  { section: 'Revenue', items: [
    { id: 'memberships', label: 'Memberships', icon: 'member' },
    { id: 'campaigns', label: 'Campaigns', icon: 'mail' },
  ]},
  { section: 'Catalogue', items: [
    { id: 'wines', label: 'Wine catalogue', icon: 'glass' },
    { id: 'uploads', label: 'Portal uploads', icon: 'upload' },
  ]},
  { section: 'Operate', items: [
    { id: 'support', label: 'Support', icon: 'ticket', count: (s) => s.t('tickets').filter((t) => t.status !== 'closed').length },
    { id: 'analytics', label: 'Analytics', icon: 'chart' },
    { id: 'admin', label: 'Backup & admin', icon: 'database' },
  ]},
];

function Sidebar({ route }) {
  const store = useStore();
  return (
    <nav className="sidebar">
      <div className="side-brand">
        <div className="side-wordmark">AI<span className="dot"></span>Wine<span className="suffix">CRM</span></div>
      </div>
      {NAV.map((sec) => (
        <React.Fragment key={sec.section}>
          <div className="side-section">{sec.section}</div>
          <div className="side-nav">
            {sec.items.map((it) => (
              <button key={it.id} className={'side-link' + (route.page === it.id ? ' active' : '')} onClick={() => window.go(it.id)}>
                <Ic name={it.icon} w={17} />
                {it.label}
                {it.count != null && it.count(store) > 0 && <span className="count">{it.count(store)}</span>}
              </button>
            ))}
          </div>
        </React.Fragment>
      ))}
      <div className="side-foot">
        {store.mode === 'demo'
          ? ((store.cache.settings || {}).dataset === 'real'
            ? <span className="badge badge-brass" style={{ alignSelf: 'flex-start' }} title="Your real winery list, stored in this browser — deploy Supabase to share it with the team"><span className="dot pulse"></span>Real data · local</span>
            : <span className="badge badge-brass" style={{ alignSelf: 'flex-start' }}><span className="dot pulse"></span>Demo data</span>)
          : <span className="badge badge-green" style={{ alignSelf: 'flex-start' }}><span className="dot"></span>Live · Supabase</span>}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <window.UI.Avatar name={store.user ? store.user.name : '?'} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--bone)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{store.user ? store.user.name : ''}</div>
            <div className="mono" style={{ fontSize: 9.5, color: 'rgba(244,239,229,0.5)', letterSpacing: '0.08em' }}>{store.user ? (store.user.role || 'member').toUpperCase() : ''}</div>
          </div>
          <button className="btn-quiet" style={{ color: 'rgba(244,239,229,0.6)' }} title="Sign out" onClick={() => store.signOut()}><Ic name="logout" w={16} /></button>
        </div>
      </div>
    </nav>
  );
}

/* ---------- topbar ---------- */
function Topbar({ country, setCountry }) {
  const store = useStore();
  const [q, setQ] = React.useState('');
  const results = React.useMemo(() => {
    if (q.trim().length < 2) return [];
    const needle = q.trim().toLowerCase();
    const hit = (s) => (s || '').toLowerCase().includes(needle);
    const out = [];
    store.t('wineries').forEach((w) => { if (hit(w.name) || hit(w.region)) out.push({ label: w.name, sub: w.region + ' · ' + w.country, page: 'wineries', id: w.id }); });
    store.t('contacts').forEach((c) => { if (hit(c.name) || hit(c.email)) { const w = store.get('wineries', c.wineryId); out.push({ label: c.name, sub: (w ? w.name : '') + ' · contact', page: 'wineries', id: c.wineryId }); } });
    store.t('consumers').forEach((c) => { if (hit(c.name) || hit(c.email)) out.push({ label: c.name, sub: 'Consumer · ' + c.country, page: 'consumers', id: c.id }); });
    return out.slice(0, 8);
  }, [q]);

  return (
    <header className="topbar">
      <div className="searchbox" style={{ position: 'relative' }}>
        <Ic name="search" w={15} />
        <input className="input" placeholder="Search wineries, contacts, consumers…" value={q} onChange={(e) => setQ(e.target.value)} />
        {results.length > 0 && (
          <div className="card" style={{ position: 'absolute', top: '110%', left: 0, right: 0, zIndex: 60, boxShadow: '0 20px 40px rgba(27,20,16,0.18)', overflow: 'hidden' }}>
            {results.map((r, i) => (
              <button key={i} className="btn-quiet" style={{ display: 'flex', width: '100%', justifyContent: 'space-between', padding: '9px 14px', borderBottom: '1px solid var(--line-soft)', borderRadius: 0 }}
                onClick={() => { setQ(''); window.go(r.page, r.id); }}>
                <span style={{ fontWeight: 600, fontSize: 13 }}>{r.label}</span>
                <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>{r.sub}</span>
              </button>
            ))}
          </div>
        )}
      </div>
      <div style={{ flex: 1 }}></div>
      <span className="label" style={{ fontSize: 9.5 }}>Market</span>
      <Seg mono options={[{ value: 'ALL', label: 'All' }, { value: 'NZ', label: 'NZ' }, { value: 'AU', label: 'AU' }]} value={country} onChange={setCountry} />
    </header>
  );
}

Object.assign(window, { useRoute, Login, Sidebar, Topbar });
