// App principal: Login + Shell + roteamento de views + Tweaks
const { useState: useSt, useEffect: useEf, useRef: useRf } = React;

const ACCENT_PALETTES = {
  verde:  { c: "oklch(55% 0.085 165)", c2: "oklch(70% 0.06 165)",  cs: "oklch(95% 0.025 165)", ci: "oklch(35% 0.06 165)", warn: "oklch(58% 0.12 45)",  warnSoft: "oklch(95% 0.04 50)"  },
  azul:   { c: "oklch(55% 0.10 240)",  c2: "oklch(70% 0.07 240)",  cs: "oklch(95% 0.03 240)",  ci: "oklch(35% 0.07 240)",  warn: "oklch(58% 0.12 45)",  warnSoft: "oklch(95% 0.04 50)"  },
  ambar:  { c: "oklch(58% 0.12 65)",   c2: "oklch(72% 0.08 65)",   cs: "oklch(95% 0.04 70)",   ci: "oklch(38% 0.08 60)",   warn: "oklch(56% 0.16 28)",  warnSoft: "oklch(96% 0.03 28)"  },
  indigo: { c: "oklch(52% 0.13 290)",  c2: "oklch(68% 0.08 290)",  cs: "oklch(95% 0.035 290)", ci: "oklch(34% 0.09 290)",  warn: "oklch(58% 0.12 45)",  warnSoft: "oklch(95% 0.04 50)"  },
};

function detectMobileDevice() {
  const ua = navigator.userAgent || "";
  const uaMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile/i.test(ua);
  const narrow = window.matchMedia("(max-width: 760px)").matches;
  const coarse = window.matchMedia("(pointer: coarse)").matches;
  return narrow || (uaMobile && coarse);
}

function useDeviceClass() {
  const [isMobile, setIsMobile] = useSt(false);
  useEf(() => {
    function update() {
      const next = detectMobileDevice();
      document.body.dataset.device = next ? "mobile" : "desktop";
      setIsMobile(next);
    }
    update();
    window.addEventListener("resize", update);
    window.addEventListener("orientationchange", update);
    return () => {
      window.removeEventListener("resize", update);
      window.removeEventListener("orientationchange", update);
    };
  }, []);
  return isMobile;
}

// ─── Loading screen ────────────────────────────────────────────
function LoadingScreen({ error, onRetry }) {
  return (
    <div className="loading">
      <div className="loading__brand">
        <div className="loading__brand-mark" />
        farma
      </div>
      {error ? (
        <>
          <p className="loading__error">{error}</p>
          <button className="loading__retry" onClick={onRetry}>Tentar novamente</button>
        </>
      ) : (
        <p className="loading__msg">Carregando dados…</p>
      )}
    </div>
  );
}

// ─── Login ────────────────────────────────────────────────────
function LoginScreen({ onLogin }) {
  const [email, setEmail] = useSt("ana.marketing@farma.io");
  const [pass, setPass] = useSt("••••••••");
  const [busy, setBusy] = useSt(false);

  function submit(e) {
    e.preventDefault();
    if (!email || !pass) return;
    setBusy(true);
    setTimeout(() => onLogin({ email }), 650);
  }

  const yyyy = new Date().getFullYear();

  return (
    <div className="login">
      <div className="login__left">
        <div className="login__brand">
          <div className="login__brand-mark" />
          farma
        </div>
        <div>
          <h1 className="login__hero">Dados que viram <em>decisão</em>.<br/>Não relatório.</h1>
          <p className="login__sub">Plataforma de inteligência farmacêutica para times de marketing — mapeie demanda, antecipe rupturas e entenda a jornada de cada paciente.</p>
        </div>
        <div className="login__meta">
          <span className="login__dot" />
          <span>{yyyy} · farma - aulerlabs product</span>
        </div>
      </div>
      <div className="login__right">
        <form className="login__card" onSubmit={submit}>
          <h2 className="login__title">Entrar</h2>
          <p className="login__hint">Acesse seu painel de inteligência farmacêutica.</p>
          <div className="field">
            <label className="field__label">E-mail corporativo</label>
            <input className="field__input" type="email" value={email} onChange={e => setEmail(e.target.value)} autoFocus />
          </div>
          <div className="field">
            <div className="field__row">
              <label className="field__label">Senha</label>
              <a href="#">Esqueci a senha</a>
            </div>
            <input className="field__input" type="password" value={pass} onChange={e => setPass(e.target.value)} />
          </div>
          <button className="btn-primary" type="submit" disabled={busy}>
            {busy ? "Entrando…" : <>Entrar <span className="arrow">→</span></>}
          </button>
          <div className="login__sso">ou continue com <a href="#">SSO corporativo</a></div>
        </form>
      </div>
    </div>
  );
}

// ─── Drug picker ─────────────────────────────────────────────
function DrugPicker({ drug, onChange }) {
  const [open, setOpen] = useSt(false);
  const ref = useRf(null);
  useEf(() => {
    function click(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener("mousedown", click);
    return () => document.removeEventListener("mousedown", click);
  }, []);

  const drugs = window.FARMA_DATA.drugs;
  return (
    <div ref={ref} style={{ position: "relative", marginLeft: "auto" }}>
      <button className="drug-picker" onClick={() => setOpen(o => !o)}>
        <span className="drug-picker__dot" />
        <span className="drug-picker__name">{drug.name}</span>
        <span className="drug-picker__brand">· {drug.brand}</span>
        <svg className="drug-picker__chev" width="10" height="10" viewBox="0 0 10 10">
          <path d="M2 4 L5 7 L8 4" stroke="currentColor" fill="none" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </button>
      {open && (
        <div className="drug-menu">
          {drugs.map(d => (
            <button key={d.id} className={`drug-menu__item ${d.id === drug.id ? "is-active" : ""}`}
              disabled={!d.active}
              onClick={() => { if (d.active) { onChange(d); setOpen(false); } }}>
              <span style={{ width: 8, height: 8, borderRadius: 999, background: d.active ? "var(--accent)" : "var(--ink-4)" }} />
              <div>
                <div className={"drug-menu__name " + (d.active ? "" : "drug-menu__inactive")}>
                  {d.name} <span style={{ color: "var(--ink-4)", fontWeight: 400 }}>· {d.brand}</span>
                </div>
                <div className="drug-menu__class">{d.class}</div>
              </div>
              {!d.active && <span className="drug-menu__tag">em breve</span>}
              {d.active && d.id === drug.id && <span className="drug-menu__tag" style={{ background: "var(--accent-soft)", borderColor: "transparent", color: "var(--accent-ink)" }}>atual</span>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Dashboard shell ─────────────────────────────────────────
function Dashboard({ user, onLogout, initialView = "demanda", showInsight = true, isMobile = false }) {
  const [drug, setDrug] = useSt(window.FARMA_DATA.drugs[0]);
  const [view, setView] = useSt(initialView);
  const [market, setMarket] = useSt("Todos");
  const [period, setPeriod] = useSt("M");

  // Sync date from data
  const syncDate = window.FARMA_DATA.kpis?.competencia || "—";
  const syncShort = syncDate.split("/").map(s => s.trim()).reverse().join("/").slice(0, 7);

  const initials = user.email.split("@")[0].split(".").map(s => s[0]).join("").slice(0, 2).toUpperCase();

  const navItems = [
    { id: "demanda",   label: "Demanda",        icon: NavIconMap,      count: window.FARMA_DATA.kpis?.ufsAtendidas + " UFs" },
    { id: "pacientes", label: "Pacientes",       icon: NavIconUsers,    count: (window.FARMA_DATA.kpis?.pacientesAtivos / 1000).toFixed(1).replace(".", ",") + "k" },
    { id: "hospitais", label: isMobile ? "Hosp." : "Hospitais", icon: NavIconHospital, count: window.FARMA_DATA.kpis?.estabsAtivos },
    { id: "exames",    label: "Exames",          icon: NavIconFlask,    count: "20k" },
    { id: "ied",       label: isMobile ? "Intern." : "Internações IEP", icon: NavIconHeart, count: (window.FARMA_DATA.internacoes?.total / 1000).toFixed(1).replace(".", ",") + "k" },
  ];

  const periodOptions = isMobile
    ? [{ id: "M", label: "Mês" }, { id: "3M", label: "3m" }, { id: "12M", label: "12m" }, { id: "YTD", label: "YTD" }]
    : [{ id: "M", label: "Mês corrente" }, { id: "3M", label: "3 meses" }, { id: "12M", label: "12 meses" }, { id: "YTD", label: "YTD" }];

  return (
    <div className={`shell ${isMobile ? "is-mobile" : ""}`}>
      <div className="topbar">
        <div className="topbar__brand"><div className="topbar__brand-mark" />farma</div>
        <div className="topbar__crumbs">
          <span>Painéis</span><span className="sep">/</span>
          <span>{drug.name}</span><span className="sep">/</span>
          <span className="now">{{ demanda: "Demanda", pacientes: "Pacientes", hospitais: "Hospitais", exames: "Exames", ied: "Internações IEP" }[view] || "—"}</span>
        </div>
        <DrugPicker drug={drug} onChange={setDrug} />
        <div className="topbar__user" title={user.email}>{initials}</div>
      </div>

      <aside className="sidenav">
        <div className="sidenav__group">Painéis</div>
        {navItems.map(it => (
          <button key={it.id} className={`sidenav__item ${view === it.id ? "is-active" : ""}`} onClick={() => setView(it.id)}>
            <span className="ic"><it.icon /></span>
            <span>{it.label}</span>
            {it.count && <span className="sidenav__count">{it.count}</span>}
          </button>
        ))}
        <div className="sidenav__divider" />
        <div className="sidenav__group">Conta</div>
        <button className="sidenav__item"><span className="ic"><NavIconCog /></span><span>Configurações</span></button>
        <button className="sidenav__item" onClick={onLogout}><span className="ic"><NavIconLogout /></span><span>Sair</span></button>
        <div className="sidenav__status">
          <span className="sidenav__status-dot" />
          <span>Sincronizado</span>
          <span className="sidenav__status-meta">{syncShort}</span>
        </div>
      </aside>

      <main className="canvas">
        <div className="filters">
          <span className="card__meta" style={{ marginRight: 6 }}>FILTRAR</span>
          {["Todos", "Fibrose Cística", "IEP"].map(m => (
            <button key={m} className={`chip ${market === m ? "is-active" : ""}`} onClick={() => setMarket(m)}>
              {m !== "Todos" && <span className="chip__dot" style={{ background: m === "Fibrose Cística" ? "oklch(60% 0.10 200)" : "oklch(60% 0.10 35)" }} />}
              {m}
            </button>
          ))}
          <div style={{ width: 1, height: 22, background: "var(--hairline)", margin: "0 6px" }} />
          {periodOptions.map(p => (
            <button key={p.id} className={`chip ${period === p.id ? "is-active" : ""}`} onClick={() => setPeriod(p.id)}>{p.label}</button>
          ))}
        </div>
        {view === "demanda"   && <DemandaView market={market} period={period} showInsight={showInsight} />}
        {view === "pacientes" && <PacientesView market={market} period={period} />}
        {view === "hospitais" && <HospitaisView />}
        {view === "exames"    && <ExamesView />}
        {view === "ied"       && <InternacoesView />}
      </main>
    </div>
  );
}

// ─── Ícones ───────────────────────────────────────────────────
function NavIconMap()     { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" strokeLinecap="round"><path d="M5 2 L1 4 V14 L5 12 L11 14 L15 12 V2 L11 4 Z M5 2 V12 M11 4 V14"/></svg>; }
function NavIconUsers()   { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" strokeLinecap="round"><circle cx="6" cy="5" r="2.5"/><path d="M2 13 C2 10.5 4 9 6 9 C8 9 10 10.5 10 13"/><circle cx="11" cy="6" r="2"/><path d="M11 9 C13 9 14 10.5 14 12"/></svg>; }
function NavIconHospital(){ return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" strokeLinecap="round"><rect x="2" y="3" width="12" height="11" rx="1"/><path d="M8 6 V11 M5.5 8.5 H10.5"/></svg>; }
function NavIconFlask()   { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" strokeLinecap="round"><path d="M6 2 V7 L3 13 C2.6 13.7 3.1 14.5 4 14.5 H12 C12.9 14.5 13.4 13.7 13 13 L10 7 V2 M5 2 H11"/></svg>; }
function NavIconHeart()   { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" strokeLinecap="round"><path d="M8 13.5 C8 13.5 2 10 2 6 C2 4 3.5 2.5 5.5 2.5 C6.8 2.5 7.5 3.3 8 4 C8.5 3.3 9.2 2.5 10.5 2.5 C12.5 2.5 14 4 14 6 C14 10 8 13.5 8 13.5 Z"/></svg>; }
function NavIconCog()     { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" strokeLinecap="round"><circle cx="8" cy="8" r="2"/><path d="M8 2 V4 M8 12 V14 M2 8 H4 M12 8 H14 M3.5 3.5 L5 5 M11 11 L12.5 12.5 M3.5 12.5 L5 11 M11 5 L12.5 3.5"/></svg>; }
function NavIconLogout()  { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" strokeLinecap="round"><path d="M10 4 V3 C10 2.4 9.6 2 9 2 H3 C2.4 2 2 2.4 2 3 V13 C2 13.6 2.4 14 3 14 H9 C9.6 14 10 13.6 10 13 V12 M6 8 H14 M11 5 L14 8 L11 11"/></svg>; }

// ─── App root ─────────────────────────────────────────────────
function App() {
  const [t, setTweak] = useTweaks(window.TWEAK_DEFAULTS);
  const [user, setUser] = useSt(null);
  const [toast, setToast] = useSt(null);
  const [ready, setReady] = useSt(!window.__FARMA_LOADING);
  const [loadError, setLoadError] = useSt(null);
  const isMobile = useDeviceClass();

  // Aguarda dados da API
  useEf(() => {
    if (ready) return;
    function onReady() { setReady(true); }
    window.addEventListener("farma:ready", onReady);
    return () => window.removeEventListener("farma:ready", onReady);
  }, [ready]);

  // Aplica tweaks como CSS variables
  useEf(() => {
    const root = document.documentElement.style;
    const p = ACCENT_PALETTES[t.accent] || ACCENT_PALETTES.verde;
    root.setProperty("--accent", p.c);
    root.setProperty("--accent-2", p.c2);
    root.setProperty("--accent-soft", p.cs);
    root.setProperty("--accent-ink", p.ci);
    root.setProperty("--r-lg", t.radius + "px");
    root.setProperty("--r-md", Math.max(6, t.radius - 4) + "px");
    root.setProperty("--r-sm", Math.max(4, t.radius - 8) + "px");
    root.setProperty("--display-weight", String(t.displayWeight));
    document.body.dataset.density = t.density;
  }, [t.accent, t.radius, t.displayWeight, t.density]);

  useEf(() => {
    if (toast) {
      const tm = setTimeout(() => setToast(null), 2200);
      return () => clearTimeout(tm);
    }
  }, [toast]);

  if (!ready) {
    return <LoadingScreen error={loadError} onRetry={() => { window.location.reload(); }} />;
  }

  if (!user) return (
    <>
      <LoginScreen onLogin={u => { setUser(u); setToast("Bem-vinda, " + u.email.split("@")[0].split(".")[0]); }} />
      <FarmaTweaks t={t} setTweak={setTweak} />
    </>
  );

  return (
    <>
      <Dashboard user={user} onLogout={() => setUser(null)} initialView={t.defaultView} showInsight={t.showInsight} isMobile={isMobile} />
      {toast && <div className="toast"><span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--accent-2)" }} />{toast}</div>}
      <FarmaTweaks t={t} setTweak={setTweak} />
    </>
  );
}

function FarmaTweaks({ t, setTweak }) {
  return (
    <TweaksPanel>
      <TweakSection label="Aparência" />
      <TweakRadio label="Cor de acento" value={t.accent} options={["verde", "azul", "ambar", "indigo"]} onChange={v => setTweak("accent", v)} />
      <TweakRadio label="Densidade" value={t.density} options={["compact", "regular"]} onChange={v => setTweak("density", v)} />
      <TweakSlider label="Cantos arredondados" value={t.radius} min={4} max={24} step={1} unit="px" onChange={v => setTweak("radius", v)} />
      <TweakSlider label="Peso de display" value={t.displayWeight} min={300} max={700} step={100} onChange={v => setTweak("displayWeight", v)} />
      <TweakSection label="Conteúdo" />
      <TweakToggle label="Banner de insight" value={t.showInsight} onChange={v => setTweak("showInsight", v)} />
      <TweakRadio label="Visão padrão" value={t.defaultView} options={["demanda", "pacientes"]} onChange={v => setTweak("defaultView", v)} />
    </TweaksPanel>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
