/* FrontCall Hub — owner app root (navigation). */

function titleForTab(tab) {
  return { dashboard: ["EverTrust Cleaning", "Sexta-feira, 5 de junho"], calls: ["Ligações", "Hoje · 12 atendidas"], messages: ["Mensagens", "SMS com seus clientes"], leads: ["Clientes", "Funil + carteira"], agenda: ["Agenda", "Esta semana"], more: ["Mais", null] }[tab];
}

function App() {
  const [tab, setTab] = React.useState("dashboard");
  const [stack, setStack] = React.useState([]); // detail stack: {view, param}
  const scrollRef = React.useRef(null);

  const resetScroll = () => { if (scrollRef.current) scrollRef.current.scrollTop = 0; };

  const go = (view, param) => {
    if (["dashboard", "calls", "messages", "leads", "agenda", "more"].includes(view)) {
      setStack([]); setTab(view); resetScroll(); return;
    }
    setStack((s) => [...s, { view, param }]); resetScroll();
  };
  const back = () => { setStack((s) => s.slice(0, -1)); resetScroll(); };
  const onTab = (t) => { setStack([]); setTab(t); resetScroll(); };

  const top = stack[stack.length - 1];

  let header, body;
  if (top) {
    if (top.view === "call") {
      const c = window.FCData.calls.find((x) => x.id === top.param);
      header = <AppHeader onBack={back} title={c ? c.name : "Ligação"} subtitle={c ? `${c.date} · ${c.time}` : ""} right={<LeadQualityBadge quality={c ? c.quality : "warm"} size="sm" />} />;
      body = <CallDetailScreen key={top.param} id={top.param} go={go} />;
    } else if (top.view === "lead" || top.view === "client") {
      header = <AppHeader onBack={back} title="Cliente" />;
      body = <ClientDetailScreen key={top.param} id={top.param} go={go} />;
    } else if (top.view === "job") {
      const a = window.FCData.appointments.concat(window.FCSched ? window.FCSched.extras : []).find((x) => x.id === top.param);
      header = <AppHeader onBack={back} title={a ? a.name : "Visita"} subtitle={a ? `${a.service} · ${a.date}` : ""} />;
      body = <JobDetailScreen key={top.param} id={top.param} go={go} />;
    } else if (top.view === "occ") {
      const o = window.schedAllOccs ? window.schedAllOccs().find((x) => x.key === top.param) : null;
      header = <AppHeader onBack={back} title={o ? o.name : "Visita"} subtitle={o ? `${o.service} · ${o.date}` : ""} />;
      body = <OccurrenceScreen key={top.param} occKey={top.param} go={go} />;
    } else if (top.view === "chat") {
      const t = (window.FCThreads || []).find((x) => x.id === top.param);
      const cRel = t && t.clientId ? ((window.FCData.clients.find((c) => c.id === t.clientId) || {}).relation || null) : null;
      const relLabel = cRel === "ativo" ? " · cliente" : cRel === "lead" ? " · lead no funil" : cRel === "inativo" ? " · inativo" : "";
      header = <AppHeader onBack={back} title={t ? t.name : "Conversa"} subtitle={t && t.kind === "riley" ? "Avisos automáticos · em português" : `SMS · em inglês${relLabel}`}
        right={t && t.clientId ? <button onClick={() => go("client", t.clientId)} style={{ border: "none", background: "var(--surface-sunken)", width: 38, height: 38, borderRadius: "var(--radius-full)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}><Icon name="user-round" size={18} color="var(--text-strong)" /></button> : null} />;
      body = <ChatPanel key={top.param} id={top.param} go={go} />;
    } else if (top.view === "addlead") {
      header = <AppHeader onBack={back} title="Adicionar" subtitle="Lead em negociação ou cliente que já fechou" />;
      body = <AddLeadScreen go={go} initialMode={top.param} />;
    } else if (top.view === "team") {
      header = <AppHeader onBack={back} title="Equipe & acessos" subtitle="Quem vê o quê — você no controle" />;
      body = <TeamAccessScreen key={String(top.param || "t")} go={go} />;
    } else if (top.view === "invite") {
      header = <AppHeader onBack={back} title="Convidar cleaner" subtitle="Por SMS · sem conta, sem instalar nada" />;
      body = <InviteScreen key={String(top.param || "i")} go={go} jobId={top.param} />;
    } else if (top.view === "assign") {
      header = <AppHeader onBack={back} title="Atribuir cleaner" />;
      body = <AssignScreen key={String(top.param)} go={go} jobId={top.param} />;
    } else if (top.view === "workerview") {
      header = <AppHeader onBack={back} title="Como a cleaner vê" subtitle="Prévia do link mágico · acesso limitado" />;
      body = <WorkerJobView key={String(top.param)} jobId={top.param} go={go} />;
    } else if (top.view === "agent") {
      header = <AppHeader onBack={back} title="Meu Agente" subtitle="Riley · sua recepcionista" />;
      body = <AgentScreen go={go} />;
    } else if (top.view === "settings") {
      header = <AppHeader onBack={back} title="Configurações" />;
      body = <SettingsScreen go={go} />;
    } else if (top.view === "notifications") {
      header = <AppHeader onBack={back} title="Notificações" />;
      body = <NotificationsScreen go={go} />;
    } else if (top.view === "billing") {
      header = <AppHeader onBack={back} title="Plano & cobrança" />;
      body = <BillingScreen go={go} />;
    } else if (top.view === "plans") {
      header = <AppHeader onBack={back} title="Planos de recorrência" subtitle="Dia fixo entra sozinho · flexível você encaixa" />;
      body = <PlansScreen go={go} />;
    }
  } else {
    const [t, sub] = titleForTab(tab);
    const right = tab === "dashboard"
      ? <button style={{ border: "none", background: "var(--surface-sunken)", width: 38, height: 38, borderRadius: "var(--radius-full)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", position: "relative" }}>
          <Icon name="bell" size={19} color="var(--text-strong)" />
          <span style={{ position: "absolute", top: 8, right: 9, width: 8, height: 8, borderRadius: "var(--radius-full)", background: "var(--hot-500)", border: "1.5px solid var(--surface-card)" }} />
        </button>
      : (tab === "calls")
        ? <button style={{ border: "none", background: "var(--surface-sunken)", width: 38, height: 38, borderRadius: "var(--radius-full)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}><Icon name="search" size={19} color="var(--text-strong)" /></button>
        : (tab === "leads")
          ? <button onClick={() => go("addlead", window.__clientsView === "carteira" ? "cliente" : "lead")} style={{ border: "none", background: "var(--brand)", width: 38, height: 38, borderRadius: "var(--radius-full)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", boxShadow: "var(--shadow-brand)" }}><Icon name="plus" size={19} color="#fff" /></button>
          : (tab === "agenda")
            ? <button onClick={() => go("plans")} title="Planos de recorrência" style={{ border: "none", background: "var(--surface-sunken)", height: 38, padding: "0 14px", borderRadius: "var(--radius-full)", display: "flex", alignItems: "center", gap: 7, cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: "var(--fs-caption)", fontWeight: "var(--fw-bold)", color: "var(--text-strong)" }}>
                <Icon name="repeat" size={16} color="var(--brand)" />Planos
              </button>
            : null;
    header = <AppHeader title={t} subtitle={sub} brandMark={tab === "dashboard"} right={right} />;
    body = tab === "dashboard" ? <DashboardScreen go={go} />
      : tab === "calls" ? <CallsScreen go={go} />
      : tab === "messages" ? <MessagesScreen go={go} />
      : tab === "leads" ? <ClientsScreen go={go} />
      : tab === "agenda" ? <AgendaScreen go={go} />
      : <MoreScreen go={go} />;
  }

  return (
    <Scaler w={402} h={874}>
      <IOSDevice>
        <AppShell header={header} activeTab={tab} onTab={onTab} scrollRef={scrollRef}>
          {body}
        </AppShell>
      </IOSDevice>
    </Scaler>
  );
}

function Scaler({ w, h, children }) {
  const [scale, setScale] = React.useState(1);
  React.useLayoutEffect(() => {
    const fit = () => {
      const pad = 32;
      const s = Math.min((window.innerWidth - pad) / w, (window.innerHeight - pad) / h, 1);
      setScale(s > 0 ? s : 1);
    };
    fit();
    window.addEventListener("resize", fit);
    return () => window.removeEventListener("resize", fit);
  }, [w, h]);
  return (
    <div style={{ width: w * scale, height: h * scale }}>
      <div style={{ width: w, height: h, transform: `scale(${scale})`, transformOrigin: "top left" }}>
        {children}
      </div>
    </div>
  );
}

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