/* FrontCall Hub — owner app screens (Leads CRM, Lead detail, Agenda, More). */

const STAGES = [
  { value: "new", label: "Novo" },
  { value: "contacted", label: "Contatado" },
  { value: "scheduled", label: "Agendado" },
  { value: "done", label: "Concluído" },
  { value: "lost", label: "Perdido" },
];
const stageLabel = (s) => (STAGES.find((x) => x.value === s) || {}).label || s;

/* ============ LEADS / CRM (B5 — most important) ============ */
function LeadCard({ l, onClick }) {
  return (
    <Card interactive onClick={onClick} style={{ padding: "14px 16px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <Avatar name={l.name} size={42} />
        <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)" }}>{l.name}</span>
          </div>
          <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-muted)", marginTop: 2, display: "flex", gap: 8 }}>
            <span>{l.service}</span><span>·</span><span style={{ color: "var(--brand)", fontWeight: "var(--fw-semibold)" }}>{money(l.price)}</span>
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6, flex: "none" }}>
          <LeadQualityBadge quality={l.quality} size="sm" />
          <span style={{ fontSize: 10.5, color: "var(--text-faint)" }}>{l.when}</span>
        </div>
      </div>
    </Card>
  );
}

function LeadsScreen({ go }) {
  const [stage, setStage] = React.useState("new");
  const counts = {};
  STAGES.forEach((s) => { counts[s.value] = D.leads.filter((l) => l.stage === s.value).length; });
  const items = D.leads.filter((l) => l.stage === stage);
  return (
    <div style={{ padding: "12px 16px 24px" }}>
      <div style={{ marginBottom: 14 }}>
        <SegmentedTabs scroll value={stage} onChange={setStage} size="sm" style={{ width: "100%" }}
          items={STAGES.map((s) => ({ value: s.value, label: s.label, count: counts[s.value] || undefined }))} />
      </div>
      {items.length === 0 ? (
        <Card inset><EmptyState art={<WaveBars />} title="Nada por aqui" description={`Nenhum lead em "${stageLabel(stage)}" agora.`} /></Card>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {items.map((l) => <LeadCard key={l.id} l={l} onClick={() => go("lead", l.id)} />)}
        </div>
      )}
    </div>
  );
}

/* ============ LEAD DETAIL ============ */
function LeadDetailScreen({ id, go }) {
  const lead = D.leads.find((x) => x.id === id);
  const [stage, setStage] = React.useState(lead ? lead.stage : "new");
  if (!lead) return null;
  return (
    <div style={{ padding: "16px 16px 28px", display: "flex", flexDirection: "column", gap: 18 }}>
      <Card>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <Avatar name={lead.name} size={56} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: "var(--fs-h3)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-tight)", color: "var(--text-strong)" }}>{lead.name}</div>
            <div style={{ display: "flex", gap: 8, marginTop: 6, alignItems: "center" }}>
              <LeadQualityBadge quality={lead.quality} size="sm" />
              <Badge tone="brand">{lead.service}</Badge>
            </div>
          </div>
        </div>
        <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
          <Button block variant="primary" iconLeft={<Icon name="phone-outgoing" size={18} color="#fff" />}>Ligar</Button>
          <Button block variant="secondary" iconLeft={<Icon name="message-circle" size={18} color="var(--text-strong)" />}>SMS</Button>
        </div>
      </Card>

      <div>
        <SectionLabel>Etapa do funil</SectionLabel>
        <SegmentedTabs scroll value={stage} onChange={setStage} size="sm" style={{ width: "100%" }}
          items={STAGES.map((s) => ({ value: s.value, label: s.label }))} />
        {stage === "scheduled" && (
          <div style={{ marginTop: 10, display: "flex", alignItems: "center", gap: 8, color: "var(--success-600)", fontSize: "var(--fs-sm)", fontWeight: "var(--fw-semibold)" }}>
            <Icon name="calendar-check" size={16} color="var(--success-600)" /> Visita criada na Agenda
          </div>
        )}
      </div>

      <Card>
        <SectionLabel>Detalhes</SectionLabel>
        <KV k="Telefone" v={<span style={{ fontFamily: "var(--font-mono)", fontSize: "var(--fs-sm)" }}>{lead.phone}</span>} />
        <KV k="Endereço" v={lead.address} />
        <KV k="Cotação" v={<span style={{ color: "var(--brand)", fontWeight: "var(--fw-bold)" }}>{money(lead.price)}</span>} />
        <KV k="Origem" v={lead.source} />
      </Card>

      {lead.callId && (
        <Card interactive onClick={() => go("call", lead.callId)} style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ width: 40, height: 40, borderRadius: "var(--radius-full)", background: "var(--surface-brand-subtle)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
            <Icon name="phone-incoming" size={19} color="var(--brand)" />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: "var(--fw-semibold)", color: "var(--text-strong)", fontSize: "var(--fs-sm)" }}>Ligação de origem</div>
            <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-muted)" }}>Ouvir áudio + transcript</div>
          </div>
          <Icon name="chevron-right" size={18} color="var(--text-faint)" />
        </Card>
      )}

      <Button block variant="primary" size="lg" iconLeft={<Icon name="calendar" size={18} color="#fff" />}>Agendar visita</Button>
    </div>
  );
}

/* ============ AGENDA (B6) ============ */
function AgendaScreen({ go }) {
  const [appts, setAppts] = React.useState(D.appointments);
  const [kindF, setKindF] = React.useState("all");
  const confirm = (id) => setAppts((a) => a.map((x) => (x.id === id ? { ...x, status: "confirmed" } : x)));
  const shown = appts.filter((a) => kindF === "all" || a.kind === kindF);
  const groups = {};
  shown.forEach((a) => { (groups[a.date] = groups[a.date] || []).push(a); });
  const pending = appts.filter((a) => a.status === "pending").length;
  return (
    <div style={{ padding: "12px 16px 24px", display: "flex", flexDirection: "column", gap: 18 }}>
      <SegmentedTabs value={kindF} onChange={setKindF} size="sm" style={{ width: "100%" }} items={[
        { value: "all", label: "Tudo", count: appts.length },
        { value: "job", label: "Serviços", count: appts.filter((a) => a.kind === "job").length },
        { value: "estimate", label: "Orçamentos", count: appts.filter((a) => a.kind === "estimate").length },
      ]} />
      {pending > 0 && (
        <div style={{ background: "var(--warm-bg)", border: "1px solid color-mix(in oklab, var(--warm-500) 30%, white)", borderRadius: "var(--radius-md)", padding: "12px 16px", display: "flex", alignItems: "center", gap: 10 }}>
          <Icon name="clock" size={18} color="var(--warm-600)" />
          <span style={{ fontSize: "var(--fs-sm)", color: "var(--text-primary)", fontWeight: "var(--fw-medium)" }}>{pending} visita(s) aguardando sua confirmação</span>
        </div>
      )}
      {Object.keys(groups).map((date) => (
        <div key={date}>
          <SectionLabel>{date}</SectionLabel>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {groups[date].map((a) => (
              <Card key={a.id} interactive onClick={() => go("job", a.id)} style={{ padding: "14px 16px" }}>
                <div style={{ display: "flex", gap: 14 }}>
                  <div style={{ flex: "none", textAlign: "center", minWidth: 56 }}>
                    <div style={{ fontFamily: "var(--font-mono)", fontWeight: "var(--fw-bold)", color: "var(--text-strong)", fontSize: "var(--fs-body)" }}>{a.time.replace(" ", "")}</div>
                    <div style={{ fontSize: 10.5, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: "var(--ls-wide)" }}>{a.window}</div>
                  </div>
                  <div style={{ width: 1, background: "var(--border-subtle)" }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
                      <span style={{ fontWeight: "var(--fw-semibold)", color: "var(--text-strong)", fontSize: "var(--fs-body)" }}>{a.name}</span>
                      <span style={{ display: "inline-flex", gap: 6 }}>
                        {window.jobKindBadge && window.jobKindBadge(a.kind)}
                        {(window.FCJobs && window.FCJobs[a.id] && window.FCJobs[a.id].stage !== "scheduled" && window.jobStatusBadge)
                          ? window.jobStatusBadge(window.FCJobs[a.id].stage, a.kind)
                          : a.status === "confirmed"
                            ? <Badge tone="success" dot>Confirmada</Badge>
                            : <Badge tone="warning" dot>Pendente</Badge>}
                      </span>
                    </div>
                    <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-muted)", marginTop: 3, display: "flex", alignItems: "center", gap: 6 }}>
                      <Icon name="map-pin" size={13} color="var(--text-faint)" /> {a.service} · {a.address}
                    </div>
                    {a.status === "pending" && (
                      <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
                        <Button size="sm" variant="primary" onClick={(e) => { e.stopPropagation(); confirm(a.id); }} iconLeft={<Icon name="check" size={16} color="#fff" />}>Confirmar</Button>
                        <Button size="sm" variant="ghost" onClick={(e) => e.stopPropagation()} style={{ color: "var(--text-secondary)" }}>Remarcar</Button>
                      </div>
                    )}
                  </div>
                </div>
              </Card>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

/* ============ MORE / MEU AGENTE (B7 light) ============ */
function MoreScreen({ go }) {
  const rows = [
    { icon: "sparkles", label: "Meu Agente", sub: "Persona · catálogo · horário", view: "agent" },
    { icon: "repeat", label: "Planos de recorrência", sub: "Recorrências fixas e flexíveis", view: "plans" },
    { icon: "bell", label: "Notificações", sub: "Lead quente → email / SMS", view: "notifications" },
    { icon: "banknote", label: "Plano & cobrança", sub: "Pro · 500 min/mês", view: "billing" },
    { icon: "settings", label: "Configurações", sub: "Conta · número · idioma", view: "settings" },
  ];
  return (
    <div style={{ padding: "16px 16px 24px", display: "flex", flexDirection: "column", gap: 18 }}>
      <Card style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <Avatar name={D.tenant.owner} size={52} />
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: "var(--fw-bold)", color: "var(--text-strong)", fontSize: "var(--fs-body-lg)" }}>{D.tenant.owner}</div>
          <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-muted)" }}>{D.tenant.company}</div>
        </div>
        <Badge tone="success" dot>Ativo</Badge>
      </Card>

      <Card inset>
        {rows.map((r, i) => (
          <div key={r.label} onClick={() => go(r.view)} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 16px", borderBottom: i < rows.length - 1 ? "1px solid var(--border-subtle)" : "none", cursor: "pointer" }}>
            <div style={{ width: 38, height: 38, borderRadius: "var(--radius-md)", background: "var(--surface-brand-subtle)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
              <Icon name={r.icon} size={19} color="var(--brand)" />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: "var(--fw-semibold)", color: "var(--text-strong)", fontSize: "var(--fs-body)" }}>{r.label}</div>
              <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-muted)" }}>{r.sub}</div>
            </div>
            <Icon name="chevron-right" size={18} color="var(--text-faint)" />
          </div>
        ))}
      </Card>

      <div style={{ display: "flex", justifyContent: "center", padding: "8px 0" }}>
        <img src="../assets/logos/frontcall-hub-horizontal.svg" alt="FrontCall Hub" style={{ height: 26, opacity: 0.5 }} />
      </div>
    </div>
  );
}

Object.assign(window, { STAGES, LeadsScreen, LeadCard, LeadDetailScreen, AgendaScreen, MoreScreen });
