/* FrontCall Hub — owner app screens. */

const D = window.FCData;
const money = (v) => (v == null ? "—" : "$" + v);

/* ============ DASHBOARD (B2 — most important) ============ */
function DashboardScreen({ go }) {
  const t = D.today;
  return (
    <div style={{ padding: "16px 16px 24px", display: "flex", flexDirection: "column", gap: 22 }}>
      <div>
        <SectionLabel action={<span style={{ fontSize: "var(--fs-caption)", color: "var(--text-faint)" }}>Sexta, 5 jun</span>}>Hoje</SectionLabel>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <StatTile label="Ligações" value={t.calls} delta="+3" icon={<Icon name="phone" size={16} color="var(--text-faint)" />} />
          <StatTile label="Leads qualif." value={t.qualified} delta="+2" icon={<Icon name="sparkles" size={16} color="var(--text-faint)" />} />
          <StatTile label="Receita estim." unit="$" value={t.revenue} delta="+18%" icon={<Icon name="banknote" size={16} color="var(--text-faint)" />} />
          <StatTile label="Próximas visitas" value={t.nextVisits} deltaTone="neutral" delta="esta sem." icon={<Icon name="calendar-check" size={16} color="var(--text-faint)" />} />
        </div>
      </div>

      <div style={{ background: "var(--blue-600)", borderRadius: "var(--radius-lg)", padding: "16px 18px", display: "flex", alignItems: "center", gap: 14, boxShadow: "var(--shadow-brand)" }}>
        <div style={{ width: 44, height: 44, borderRadius: "var(--radius-full)", background: "rgba(255,255,255,0.18)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
          <WaveBars active size={22} color="#fff" />
        </div>
        <div style={{ flex: 1, color: "#fff" }}>
          <div style={{ fontWeight: "var(--fw-bold)", fontSize: "var(--fs-body)" }}>Riley está no ar</div>
          <div style={{ fontSize: "var(--fs-caption)", color: "rgba(255,255,255,0.85)" }}>Atendendo em inglês · {D.tenant.phone}</div>
        </div>
        <Button size="sm" variant="secondary" onClick={() => go("agent")} style={{ background: "rgba(255,255,255,0.16)", color: "#fff", border: "1px solid rgba(255,255,255,0.3)" }}>Testar</Button>
      </div>

      {window.FitNudge && <window.FitNudge go={go} />}

      <div>
        <SectionLabel action={<button onClick={() => go("calls")} style={{ border: "none", background: "none", color: "var(--text-link)", fontSize: "var(--fs-caption)", fontWeight: "var(--fw-semibold)", cursor: "pointer" }}>Ver tudo</button>}>Funil da semana</SectionLabel>
        <Card><FunnelBars data={D.funnel} /></Card>
      </div>

      <div>
        <SectionLabel>Quando ligam (dia × hora)</SectionLabel>
        <Card><Heatmap data={D.heat} /></Card>
      </div>

      <div>
        <SectionLabel>Mix de serviços</SectionLabel>
        <Card><ServiceMix data={D.serviceMix} /></Card>
      </div>
    </div>
  );
}

/* ============ CALL ROW + CALLS LIST (B3) ============ */
function CallRow({ c, onClick }) {
  const ic = callIcon(c);
  return (
    <Card interactive onClick={onClick} style={{ padding: "14px 16px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <div style={{ width: 40, height: 40, borderRadius: "var(--radius-full)", background: "var(--surface-sunken)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
          <Icon name={ic.name} size={19} color={ic.color} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ fontWeight: "var(--fw-semibold)", color: "var(--text-strong)", fontSize: "var(--fs-body)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</span>
          </div>
          <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-muted)", marginTop: 2, display: "flex", gap: 8, alignItems: "center" }}>
            <span>{c.time}</span><span>·</span><span style={{ fontFamily: "var(--font-mono)" }}>{c.dur}</span>
            {c.service !== "—" && <><span>·</span><span>{c.service}</span></>}
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6, flex: "none" }}>
          <LeadQualityBadge quality={c.quality} size="sm" />
          <Icon name="chevron-right" size={16} color="var(--text-faint)" />
        </div>
      </div>
    </Card>
  );
}

function CallsScreen({ go }) {
  const [filter, setFilter] = React.useState("all");
  const items = D.calls.filter((c) => filter === "all" || c.quality === filter);
  return (
    <div style={{ padding: "12px 16px 24px" }}>
      <div style={{ marginBottom: 14 }}>
        <SegmentedTabs scroll value={filter} onChange={setFilter} items={[
          { value: "all", label: "Todas", count: D.calls.length },
          { value: "hot", label: "Quentes", count: D.calls.filter((c) => c.quality === "hot").length },
          { value: "warm", label: "Mornos" },
          { value: "cold", label: "Frios" },
        ]} style={{ width: "100%" }} />
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {items.map((c) => <CallRow key={c.id} c={c} onClick={() => go("call", c.id)} />)}
      </div>
    </div>
  );
}

/* ============ CALL DETAIL (B4) ============ */
function KV({ k, v, big }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "9px 0", borderBottom: "1px dashed var(--border-subtle)", gap: 12 }}>
      <span style={{ color: "var(--text-muted)", fontSize: "var(--fs-sm)", flex: "none" }}>{k}</span>
      <span style={{ color: "var(--text-strong)", fontWeight: big ? "var(--fw-bold)" : "var(--fw-medium)", fontSize: big ? "var(--fs-body-lg)" : "var(--fs-body)", textAlign: "right" }}>{v}</span>
    </div>
  );
}

function CallDetailScreen({ id, go }) {
  const c = D.calls.find((x) => x.id === id);
  const [playing, setPlaying] = React.useState(false);
  if (!c) return null;
  return (
    <div style={{ padding: "16px 16px 28px", display: "flex", flexDirection: "column", gap: 18 }}>
      {/* player */}
      <Card style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ background: "var(--gray-900)", padding: "18px 18px", display: "flex", alignItems: "center", gap: 14 }}>
          <button onClick={() => setPlaying((p) => !p)} style={{ width: 48, height: 48, borderRadius: "var(--radius-full)", background: "var(--brand)", border: "none", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
            <Icon name={playing ? "pause" : "play"} size={22} color="#fff" />
          </button>
          <div style={{ flex: 1 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <WaveBars active={playing} size={22} color="var(--blue-300)" bars={5} />
              <WaveBars active={playing} size={22} color="var(--blue-300)" bars={5} />
              <WaveBars active={playing} size={22} color="var(--blue-300)" bars={5} />
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontFamily: "var(--font-mono)", fontSize: "var(--fs-caption)", color: "rgba(255,255,255,0.6)" }}>
              <span>{playing ? "0:48" : "0:00"}</span><span>{c.dur}</span>
            </div>
          </div>
        </div>
      </Card>

      {/* summary */}
      <div style={{ background: "var(--warm-bg)", borderLeft: "3px solid var(--warm-500)", borderRadius: "var(--radius-md)", padding: "12px 16px" }}>
        <div style={{ fontSize: "var(--fs-micro)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: "var(--warm-600)", marginBottom: 6 }}>Resumo da IA</div>
        <p style={{ margin: 0, fontSize: "var(--fs-sm)", lineHeight: "var(--lh-normal)", color: "var(--text-primary)" }}>{c.summary}</p>
      </div>

      {/* extracted */}
      <Card>
        <SectionLabel>Dados extraídos</SectionLabel>
        <KV k="Cliente" v={c.name} />
        <KV k="Telefone" v={<span style={{ fontFamily: "var(--font-mono)", fontSize: "var(--fs-sm)" }}>{c.phone}</span>} />
        <KV k="Serviço" v={c.service} />
        <KV k="Recorrente" v={c.recurring ? "Sim" : "Não"} />
        {c.property.beds > 0 && <KV k="Imóvel" v={`${c.property.type} · ${c.property.beds}q ${c.property.baths}b · ${c.property.sqft} sqft`} />}
        <KV k="Endereço" v={c.address} />
        {c.price && <KV k="Cotação" v={<span style={{ color: "var(--brand)", fontWeight: "var(--fw-bold)" }}>{money(c.price)}{c.accepted ? " ✓" : ""}</span>} big />}
        {c.schedule && <KV k="Visita" v={`${c.schedule.date} · ${c.schedule.time}`} big />}
      </Card>

      {c.notes && (
        <Card>
          <SectionLabel>Notas</SectionLabel>
          <p style={{ margin: 0, fontSize: "var(--fs-sm)", lineHeight: "var(--lh-normal)", color: "var(--text-secondary)" }}>{c.notes}</p>
        </Card>
      )}

      <div style={{ display: "flex", gap: 10 }}>
        <Button block variant="primary" iconLeft={<Icon name="users" size={18} color="#fff" />} onClick={() => { const cl = window.clientByCall && window.clientByCall(c.id); cl ? go("client", cl.id) : go("leads"); }}>Ver cliente</Button>
        <Button variant="secondary" iconLeft={<Icon name="x" size={18} color="var(--danger-600)" />} style={{ color: "var(--danger-600)" }}>Call ruim</Button>
      </div>
    </div>
  );
}

Object.assign(window, { DashboardScreen, CallsScreen, CallRow, CallDetailScreen, KV, money });
