/* FrontCall Hub — Detalhe de visita, com DOIS fluxos distintos:
   · SERVIÇO (kind=job): Confirmada → A caminho → Em serviço ⏱ → Finalizado
   · ORÇAMENTO (kind=estimate): Confirmada → A caminho → Avaliando → Orçamento dado
       → desfecho: Fechou (agenda o serviço na hora) / Vai pensar / Não fechou
   Estado vive em window.FCJobs pra sobreviver à navegação. */

window.FCJobs = window.FCJobs || {};

const JOB_STEPS = [
  { key: "scheduled", label: "Visita confirmada", icon: "calendar-check", hint: "Agendada pela Riley" },
  { key: "enroute", label: "A caminho", icon: "map-pin", hint: "Cliente avisado por SMS" },
  { key: "onsite", label: "Em serviço", icon: "house", hint: "Cronômetro rodando" },
  { key: "done", label: "Finalizado", icon: "circle-check-big", hint: "Cliente avisado + tempo registrado" },
];
const EST_STEPS = [
  { key: "scheduled", label: "Visita confirmada", icon: "calendar-check", hint: "Agendada pela Riley" },
  { key: "enroute", label: "A caminho", icon: "map-pin", hint: "Cliente avisado por SMS" },
  { key: "onsite", label: "Avaliando o imóvel", icon: "search", hint: "Walkthrough com o cliente" },
  { key: "done", label: "Orçamento dado", icon: "banknote", hint: "Hora de fechar" },
];
const JOB_ORDER = ["scheduled", "enroute", "onsite", "done"];

const jobSMS = (stage, a) => {
  const first = a.name.split(" ")[0];
  const cl = a.cleaner.split(" ")[0];
  if (a.kind === "estimate") {
    if (stage === "enroute") return `Hi ${first}! ${cl} from ${D.tenant.company} is on her way for your free estimate — ETA around 20 min.`;
    if (stage === "onsite") return `${cl} has arrived for your walkthrough. It takes about 30–45 minutes.`;
    return `Thanks for having us, ${first}! Your ${a.service} quote: $${a.price}. Ready when you are — just reply or call!`;
  }
  if (stage === "enroute") return `Hi ${first}! ${cl} from ${D.tenant.company} is on her way to your home — ETA around 20 min.`;
  if (stage === "onsite") return `${cl} has arrived and your ${a.service} is underway. We'll text you as soon as it's all done!`;
  return `All done, ${first}! Your home is ready — thank you for choosing ${D.tenant.company}.`;
};

const fmtClock = (ms) => new Date(ms).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
const fmtElapsed = (ms) => {
  const s = Math.floor(ms / 1000), h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), ss = s % 60;
  return (h > 0 ? h + "h " : "") + String(m).padStart(2, "0") + "m " + String(ss).padStart(2, "0") + "s";
};

function jobStatusBadge(stage, kind) {
  const est = kind === "estimate";
  if (stage === "enroute") return <Badge tone="info" dot>A caminho</Badge>;
  if (stage === "onsite") return <Badge tone="warning" dot>{est ? "Avaliando" : "Em serviço"}</Badge>;
  if (stage === "done") return <Badge tone="success" dot>{est ? "Orçamento dado" : "Finalizado"}</Badge>;
  return null;
}
function jobKindBadge(kind) {
  return kind === "estimate"
    ? <Badge tone="info">Orçamento</Badge>
    : <Badge tone="brand">Serviço</Badge>;
}

/* ---- timeline ---- */
function JobTimeline({ steps, stage, ts }) {
  const cur = JOB_ORDER.indexOf(stage);
  return (
    <Card>
      <SectionLabel>Linha do tempo</SectionLabel>
      <div style={{ display: "flex", flexDirection: "column" }}>
        {steps.map((s, i) => {
          const reached = i <= cur;
          const active = i === cur && stage !== "done";
          const last = i === steps.length - 1;
          return (
            <div key={s.key} style={{ display: "flex", gap: 14 }}>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flex: "none" }}>
                <div style={{
                  width: 34, height: 34, borderRadius: "var(--radius-full)", display: "flex", alignItems: "center", justifyContent: "center",
                  background: reached ? (active ? "var(--brand)" : "var(--success-500)") : "var(--surface-sunken)",
                  border: reached ? "none" : "1.5px solid var(--border-default)",
                }}>
                  {active
                    ? <WaveBars active size={14} color="#fff" />
                    : <Icon name={reached ? "check" : s.icon} size={16} color={reached ? "#fff" : "var(--gray-400)"} strokeWidth={reached ? 2.8 : 2} />}
                </div>
                {!last && <div style={{ width: 2, flex: 1, minHeight: 18, background: i < cur ? "var(--success-500)" : "var(--gray-200)", margin: "3px 0" }} />}
              </div>
              <div style={{ paddingBottom: last ? 0 : 16, paddingTop: 6, flex: 1 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 10 }}>
                  <span style={{ fontSize: "var(--fs-body)", fontWeight: reached ? "var(--fw-bold)" : "var(--fw-medium)", color: reached ? "var(--text-strong)" : "var(--text-faint)" }}>{s.label}</span>
                  {ts[s.key] && <span style={{ fontFamily: "var(--font-mono)", fontSize: "var(--fs-caption)", color: "var(--text-muted)", flex: "none" }}>{fmtClock(ts[s.key])}</span>}
                </div>
                <div style={{ fontSize: "var(--fs-caption)", color: reached ? "var(--text-muted)" : "var(--text-faint)", marginTop: 2 }}>{s.hint}</div>
              </div>
            </div>
          );
        })}
      </div>
    </Card>
  );
}

/* ---- desfecho do orçamento ---- */
function EstimateOutcome({ a, job, setJob, go }) {
  const decide = (outcome) => {
    const next = { ...job, outcome };
    const client = a.clientId ? D.clients.find((c) => c.id === a.clientId) : null;
    if (outcome === "won" && !job.createdJobId) {
      const nid = "a" + Math.floor(Math.random() * 9000 + 1000);
      D.appointments.push({
        id: nid, kind: "job", clientId: a.clientId, name: a.name, service: a.service,
        date: "Sex, 13 Jun", time: "9:00 AM", window: "Manhã", address: a.address,
        status: "confirmed", phone: a.phone, price: a.price, est: "4–6h", cleaner: a.cleaner,
      });
      next.createdJobId = nid;
      if (client) {
        // fechou = vira cliente na carteira, com o 1º job agendado
        client.relation = "ativo";
        client.type = client.type || "avulso";
        client.firstJob = true;
        client.apptId = nid;
        if (client.ltv == null) client.ltv = "0";
        if (client.jobsCount == null) client.jobsCount = 0;
        if (client.avgTicket == null) client.avgTicket = "—";
        client.since = client.since || "Jun 2025";
        (client.history = client.history || []).unshift({ kind: "note", date: "Hoje", label: "Fechou no orçamento 🎉", sub: "Virou cliente — 1º job Sex, 13 Jun · 9:00 AM" });
      }
    }
    if (outcome === "thinking" && client) client.stage = "proposal";
    if (outcome === "lost" && client) { client.relation = "inativo"; }
    setJob(next);
  };

  if (job.outcome === "won") {
    return (
      <React.Fragment>
        <div style={{ background: "var(--success-bg)", border: "1px solid color-mix(in oklab, var(--success-500) 28%, white)", borderRadius: "var(--radius-md)", padding: "14px 16px", display: "flex", gap: 11, alignItems: "flex-start" }}>
          <Icon name="circle-check-big" size={19} color="var(--success-600)" style={{ marginTop: 1, flexShrink: 0 }} />
          <div>
            <div style={{ fontSize: "var(--fs-sm)", fontWeight: "var(--fw-bold)", color: "var(--text-strong)" }}>Fechou! Serviço agendado 🎉</div>
            <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-secondary)", marginTop: 2 }}>Sex, 13 Jun · 9:00 AM — já está na sua Agenda como Serviço.</div>
          </div>
        </div>
        <Button block size="lg" onClick={() => job.createdJobId ? go("job", job.createdJobId) : go("agenda")} iconLeft={<Icon name="calendar-check" size={18} color="#fff" />}>Ver o serviço agendado</Button>
      </React.Fragment>
    );
  }
  if (job.outcome === "thinking") {
    return (
      <div style={{ background: "var(--warm-bg)", borderLeft: "3px solid var(--warm-500)", borderRadius: "var(--radius-md)", padding: "13px 16px" }}>
        <div style={{ fontSize: "var(--fs-sm)", fontWeight: "var(--fw-bold)", color: "var(--text-strong)" }}>Vai pensar</div>
        <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-secondary)", marginTop: 2 }}>Lead movido pra <strong>Proposta</strong> no funil — a gente te lembra de cobrar a resposta.</div>
      </div>
    );
  }
  if (job.outcome === "lost") {
    return (
      <div style={{ background: "var(--surface-sunken)", borderRadius: "var(--radius-md)", padding: "13px 16px" }}>
        <div style={{ fontSize: "var(--fs-sm)", fontWeight: "var(--fw-bold)", color: "var(--text-strong)" }}>Não fechou</div>
        <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-secondary)", marginTop: 2 }}>Movido pra <strong>Inativos</strong> na carteira. Sem stress — o próximo fecha.</div>
      </div>
    );
  }
  return (
    <Card style={{ border: "1.5px solid var(--brand)" }}>
      <div style={{ textAlign: "center", marginBottom: 14 }}>
        <div style={{ fontSize: "var(--fs-micro)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: "var(--text-muted)" }}>Orçamento dado</div>
        <div style={{ fontSize: 36, fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-tight)", color: "var(--brand)", marginTop: 4 }}>{money(a.price)}</div>
        <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-muted)", marginTop: 2 }}>{a.service} · e aí, fechou?</div>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
        <Button block size="lg" onClick={() => decide("won")} iconLeft={<Icon name="circle-check-big" size={18} color="#fff" />}>Fechou — agendar serviço</Button>
        <div style={{ display: "flex", gap: 9 }}>
          <Button block variant="secondary" onClick={() => decide("thinking")}>Vai pensar</Button>
          <Button block variant="ghost" onClick={() => decide("lost")} style={{ color: "var(--danger-600)" }}>Não fechou</Button>
        </div>
      </div>
    </Card>
  );
}

/* ---- detalhe da visita ---- */
function JobDetailScreen({ id, go }) {
  const a = D.appointments.find((x) => x.id === id) || (window.FCSched ? window.FCSched.extras.find((x) => x.id === id) : null);
  const saved = window.FCJobs[id] || { stage: "scheduled", ts: { scheduled: Date.now() - 86400000 }, sms: [], notify: true, outcome: null };
  const [job, setJobRaw] = React.useState(saved);
  const [, tick] = React.useState(0);
  const [mgr, setMgr] = React.useState(null); // "resch" | "skip" | "cancel"
  const setJob = (j) => { window.FCJobs[id] = j; setJobRaw(j); };

  React.useEffect(() => {
    if (!a || a.kind === "estimate" || job.stage !== "onsite") return;
    const t = setInterval(() => tick((n) => n + 1), 1000);
    return () => clearInterval(t);
  }, [job.stage]);

  if (!a) return null;
  const isEst = a.kind === "estimate";
  const steps = isEst ? EST_STEPS : JOB_STEPS;
  const client = a.clientId ? D.clients.find((c) => c.id === a.clientId) : null;

  // gestão da visita (remarcar / pular / cancelar) — mesmo vocabulário da ocorrência projetada
  const plan = a.planId && D.plans ? D.plans.find((p) => p.id === a.planId && p.status !== "cancelado") : null;
  const occWrap = { real: a, planId: a.planId || null, plan, clientId: a.clientId, name: a.name, date: a.date, time: a.time, address: a.address, service: a.service, price: a.price, cleaner: a.cleaner };
  const ghost = a.status === "skipped" || a.status === "canceled";
  const canManage = job.stage === "scheduled" && !ghost;
  const setStatus = (s) => { if (s !== "confirmed" && s !== "pending") a.prevStatus = a.status; a.status = s; setMgr(null); tick((n) => n + 1); };

  const advance = () => {
    const next = JOB_ORDER[JOB_ORDER.indexOf(job.stage) + 1];
    if (!next) return;
    const now = Date.now();
    const sms = job.notify ? [...job.sms, { stage: next, text: jobSMS(next, a), at: now }] : job.sms;
    // espelha o SMS automático na conversa do cliente (aba Mensagens)
    if (job.notify && window.FCThreads) {
      let th = window.FCThreads.find((t) => (a.clientId && t.clientId === a.clientId) || t.name === a.name);
      if (!th) {
        th = { id: "th-" + a.id, clientId: a.clientId, name: a.name, phone: a.phone, unread: 0, msgs: [] };
        window.FCThreads.unshift(th);
      }
      th.msgs.push({ who: "auto", text: jobSMS(next, a), at: new Date(now).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" }), tag: "Riley · automática" });
    }
    setJob({ ...job, stage: next, ts: { ...job.ts, [next]: now }, sms });
  };

  const actionLabel = isEst
    ? { scheduled: "Estou a caminho", enroute: "Cheguei — começar avaliação", onsite: "Orçamento dado" }[job.stage]
    : { scheduled: "Estou a caminho", enroute: "Cheguei — iniciar job", onsite: "Finalizar job" }[job.stage];
  const actionIcon = isEst
    ? { scheduled: "map-pin", enroute: "search", onsite: "banknote" }[job.stage]
    : { scheduled: "map-pin", enroute: "house", onsite: "circle-check-big" }[job.stage];
  const elapsed = job.ts.onsite ? (job.ts.done || Date.now()) - job.ts.onsite : 0;

  return (
    <div style={{ padding: "16px 16px 28px", display: "flex", flexDirection: "column", gap: 18 }}>
      {/* visita card */}
      <Card>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <Avatar name={a.name} size={52} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: "var(--fs-h3)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-tight)", color: "var(--text-strong)" }}>{a.name}</div>
            <div style={{ display: "flex", gap: 7, marginTop: 6, alignItems: "center", flexWrap: "wrap" }}>
              {jobKindBadge(a.kind)}
              {jobStatusBadge(job.stage, a.kind)}
            </div>
          </div>
          <div style={{ flex: "none", textAlign: "right" }}>
            <div style={{ fontSize: "var(--fs-h4)", fontWeight: "var(--fw-bold)", color: "var(--brand)" }}>{money(a.price)}</div>
            <div style={{ fontSize: "var(--fs-micro)", color: "var(--text-faint)" }}>{isEst ? "cotação da Riley" : `est. ${a.est}`}</div>
          </div>
        </div>
        <div style={{ marginTop: 16, paddingTop: 14, borderTop: "1px dashed var(--border-subtle)", display: "flex", flexDirection: "column", gap: 9 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 9, fontSize: "var(--fs-sm)", color: "var(--text-secondary)" }}>
            <Icon name="sparkles" size={15} color="var(--text-faint)" /> Serviço desejado: <span style={{ fontWeight: "var(--fw-semibold)", color: "var(--text-strong)" }}>{a.service}</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 9, fontSize: "var(--fs-sm)", color: "var(--text-secondary)" }}>
            <Icon name="calendar" size={15} color="var(--text-faint)" /> {a.date} · {a.time} <span style={{ color: "var(--text-faint)" }}>({a.window} · {a.est})</span>
            {canManage && <button onClick={() => setMgr("resch")} style={{ border: "none", background: "none", color: "var(--text-link)", fontSize: "var(--fs-caption)", fontWeight: "var(--fw-semibold)", cursor: "pointer", padding: 0, fontFamily: "var(--font-sans)" }}>Remarcar</button>}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 9, fontSize: "var(--fs-sm)", color: "var(--text-secondary)" }}>
            <Icon name="map-pin" size={15} color="var(--text-faint)" /> {a.address}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 9, fontSize: "var(--fs-sm)", color: "var(--text-secondary)" }}>
            <Icon name="user-round" size={15} color="var(--text-faint)" /> Cleaner: <span style={{ fontWeight: "var(--fw-semibold)", color: "var(--text-strong)" }}>{a.cleaner}</span>
            <button onClick={() => go("assign", a.id)} style={{ border: "none", background: "none", color: "var(--text-link)", fontSize: "var(--fs-caption)", fontWeight: "var(--fw-semibold)", cursor: "pointer", padding: 0, fontFamily: "var(--font-sans)" }}>Atribuir</button>
          </div>
        </div>
        <div style={{ display: "flex", gap: 10, marginTop: 14 }}>
          <Button block size="sm" variant="secondary" iconLeft={<Icon name="phone-outgoing" size={16} color="var(--text-strong)" />}>Ligar</Button>
          <Button block size="sm" variant="secondary" iconLeft={<Icon name="message-circle" size={16} color="var(--text-strong)" />}>SMS</Button>
        </div>
      </Card>

      {/* visita pulada / cancelada */}
      {ghost && (
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 14px", borderRadius: "var(--radius-md)", border: "1px dashed var(--border-default)", background: "var(--surface-sunken)" }}>
          <Icon name="skip-forward" size={16} color="var(--text-faint)" />
          <span style={{ flex: 1, fontSize: "var(--fs-sm)", color: "var(--text-muted)" }}>
            {a.status === "skipped" ? "Pulada — a série volta no próximo ciclo." : "Visita cancelada."}
          </span>
          <Button size="sm" variant="secondary" onClick={() => setStatus(a.prevStatus || "confirmed")}>Desfazer</Button>
        </div>
      )}

      {/* gerenciar (só antes de começar) */}
      {canManage && (
        <Card inset>
          {[
            { icon: "calendar-clock", label: "Remarcar", sub: plan ? "Só esta visita ou a série inteira" : "Escolher novo dia e horário", onClick: () => setMgr("resch") },
            plan
              ? { icon: "skip-forward", label: "Pular esta visita", sub: "Volta no próximo ciclo, no ritmo normal", warm: true, onClick: () => setMgr("skip") }
              : { icon: "x", label: "Cancelar visita", sub: "Sai da agenda — dá pra desfazer", warm: true, onClick: () => setMgr("cancel") },
            { icon: "users", label: "Trocar cleaner", sub: `Hoje: ${a.cleaner || "—"}`, onClick: () => go("assign", a.id), last: true },
          ].map((r, i) => (
            (mgr === "skip" && r.icon === "skip-forward") || (mgr === "cancel" && r.icon === "x") ? (
              <div key={r.label} style={{ display: "flex", alignItems: "center", gap: 10, padding: "13px 16px", borderBottom: r.last ? "none" : "1px solid var(--border-subtle)" }}>
                <span style={{ flex: 1, fontSize: "var(--fs-sm)", color: "var(--text-primary)", fontWeight: "var(--fw-medium)" }}>{mgr === "skip" ? `Pular ${a.date}?` : "Cancelar esta visita?"}</span>
                <Button size="sm" variant="secondary" onClick={() => setMgr(null)}>Voltar</Button>
                <Button size="sm" onClick={() => setStatus(mgr === "skip" ? "skipped" : "canceled")}>{mgr === "skip" ? "Pular" : "Cancelar"}</Button>
              </div>
            ) : (
              <button key={r.label} onClick={r.onClick} style={{ display: "flex", alignItems: "center", gap: 13, width: "100%", padding: "13px 16px", border: "none", borderBottom: r.last ? "none" : "1px solid var(--border-subtle)", background: "none", cursor: "pointer", textAlign: "left", fontFamily: "var(--font-sans)" }}>
                <div style={{ width: 36, height: 36, borderRadius: "var(--radius-md)", background: r.warm ? "var(--warm-bg)" : "var(--surface-brand-subtle)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
                  <Icon name={r.icon} size={17} color={r.warm ? "var(--warm-600)" : "var(--brand)"} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: "var(--fs-body)", fontWeight: "var(--fw-semibold)", color: "var(--text-strong)" }}>{r.label}</div>
                  <div style={{ fontSize: "var(--fs-micro)", color: "var(--text-muted)", marginTop: 1 }}>{r.sub}</div>
                </div>
                <Icon name="chevron-right" size={16} color="var(--text-faint)" />
              </button>
            )
          ))}
        </Card>
      )}

      {/* a casa (quando tem ficha do cliente) */}
      {client && (
        <Card>
          <SectionLabel action={<button onClick={() => go("client", client.id)} style={{ border: "none", background: "none", color: "var(--text-link)", fontSize: "var(--fs-caption)", fontWeight: "var(--fw-semibold)", cursor: "pointer" }}>Ver ficha</button>}>{isEst ? "O que avaliar" : "A casa"}</SectionLabel>
          <KV k="Imóvel" v={`${client.house.type} · ${client.house.beds}q ${client.house.baths}b · ${client.house.sqft.toLocaleString("en-US")} sqft`} />
          {client.house.notes.length > 0 && (
            <div style={{ display: "flex", flexWrap: "wrap", gap: 7, marginTop: 12 }}>
              {client.house.notes.map((n) => (
                <span key={n} style={{ fontSize: "var(--fs-caption)", fontWeight: "var(--fw-medium)", color: "var(--text-secondary)", background: "var(--surface-sunken)", borderRadius: "var(--radius-full)", padding: "5px 11px" }}>{n}</span>
              ))}
            </div>
          )}
        </Card>
      )}

      {/* notify toggle */}
      <Card style={{ display: "flex", alignItems: "center", gap: 12, padding: "13px 16px" }}>
        <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="zap" size={18} color="var(--brand)" />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: "var(--fw-semibold)", color: "var(--text-strong)", fontSize: "var(--fs-sm)" }}>Avisar o cliente automaticamente</div>
          <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-muted)" }}>SMS em inglês a cada etapa</div>
        </div>
        <Toggle on={job.notify} onChange={(v) => setJob({ ...job, notify: v })} />
      </Card>

      {/* timer — só pra SERVIÇO */}
      {!isEst && job.ts.onsite && (
        <Card style={{ textAlign: "center", padding: "18px 16px", background: job.stage === "onsite" ? "var(--blue-600)" : "var(--surface-card)", boxShadow: job.stage === "onsite" ? "var(--shadow-brand)" : "var(--shadow-sm)" }}>
          <div style={{ fontSize: "var(--fs-micro)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: job.stage === "onsite" ? "rgba(255,255,255,.75)" : "var(--text-muted)" }}>
            {job.stage === "onsite" ? "Tempo de serviço — rodando" : "Tempo total de serviço"}
          </div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 34, fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-tight)", color: job.stage === "onsite" ? "#fff" : "var(--text-strong)", marginTop: 6 }}>
            {fmtElapsed(elapsed)}
          </div>
          <div style={{ fontSize: "var(--fs-caption)", color: job.stage === "onsite" ? "rgba(255,255,255,.7)" : "var(--text-muted)", marginTop: 4 }}>estimativa: {a.est}</div>
        </Card>
      )}

      {/* timeline */}
      <JobTimeline steps={steps} stage={job.stage} ts={job.ts} />

      {/* sms log */}
      {job.sms.length > 0 && (
        <Card>
          <SectionLabel>Mensagens enviadas pro cliente</SectionLabel>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {job.sms.map((m, i) => (
              <div key={i} style={{ background: "var(--surface-sunken)", borderRadius: "14px 14px 14px 4px", padding: "10px 13px" }}>
                <p style={{ margin: 0, fontSize: "var(--fs-caption)", color: "var(--text-primary)", lineHeight: 1.45, fontStyle: "italic" }}>"{m.text}"</p>
                <div style={{ display: "flex", alignItems: "center", gap: 5, marginTop: 6, fontSize: "var(--fs-micro)", color: "var(--text-faint)" }}>
                  <Icon name="check" size={11} color="var(--success-600)" strokeWidth={3} /> SMS enviado · {fmtClock(m.at)}
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* ação / desfecho */}
      {ghost ? null : job.stage !== "done" ? (
        <Button block size="lg" onClick={advance} iconLeft={<Icon name={actionIcon} size={18} color="#fff" />}>{actionLabel}</Button>
      ) : isEst ? (
        <EstimateOutcome a={a} job={job} setJob={setJob} go={go} />
      ) : (
        <React.Fragment>
          <div style={{ background: "var(--success-bg)", border: "1px solid color-mix(in oklab, var(--success-500) 28%, white)", borderRadius: "var(--radius-md)", padding: "14px 16px", display: "flex", gap: 11, alignItems: "flex-start" }}>
            <Icon name="circle-check-big" size={19} color="var(--success-600)" style={{ marginTop: 1, flexShrink: 0 }} />
            <div>
              <div style={{ fontSize: "var(--fs-sm)", fontWeight: "var(--fw-bold)", color: "var(--text-strong)" }}>Job concluído em {fmtElapsed((job.ts.done || 0) - (job.ts.onsite || 0))}</div>
              <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-secondary)", marginTop: 2 }}>Tempo registrado no histórico — bom pra calibrar suas estimativas e preços.</div>
            </div>
          </div>
          <Button block size="lg" variant="secondary" onClick={() => go("agenda")}>Voltar pra agenda</Button>
        </React.Fragment>
      )}

      {mgr === "resch" && window.RescheduleSheet && <RescheduleSheet occ={occWrap} onClose={() => setMgr(null)} onDone={() => tick((n) => n + 1)} />}
    </div>
  );
}

Object.assign(window, { JobDetailScreen, JOB_STEPS, EST_STEPS, jobStatusBadge, jobKindBadge });
