/* FrontCall Hub — recorrência: bottom sheets (encaixar, remarcar, ocorrência, plano).
   Tudo ancorado dentro do frame do iPhone via portal no bezel. */

const SCH = () => window.FCSched;

/* ================= base: bottom sheet ================= */
function SchedSheet({ open, onClose, title, subtitle, children }) {
  const elRef = React.useRef(null);
  if (!elRef.current) elRef.current = document.createElement("div");
  const [shown, setShown] = React.useState(false);

  React.useEffect(() => {
    if (!open) return;
    const host = document.querySelector("[data-ios-bezel]") || document.body;
    host.appendChild(elRef.current);
    const t = requestAnimationFrame(() => setShown(true));
    return () => { cancelAnimationFrame(t); setShown(false); if (elRef.current.parentNode) elRef.current.parentNode.removeChild(elRef.current); };
  }, [open]);

  if (!open) return null;
  return ReactDOM.createPortal(
    <div style={{ position: "absolute", inset: 0, zIndex: 40, fontFamily: "var(--font-sans)" }}>
      <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(20,37,63,.4)", opacity: shown ? 1 : 0, transition: "opacity var(--dur-base) var(--ease-standard)" }} />
      <div style={{
        position: "absolute", left: 0, right: 0, bottom: 0, maxHeight: "80%",
        background: "var(--surface-card)", borderRadius: "20px 20px 0 0", boxShadow: "var(--shadow-lg)",
        display: "flex", flexDirection: "column",
        transform: shown ? "translateY(0)" : "translateY(48px)", opacity: shown ? 1 : 0,
        transition: "transform var(--dur-slow) var(--ease-standard), opacity var(--dur-base) var(--ease-standard)",
      }}>
        <div style={{ flex: "none", display: "flex", justifyContent: "center", padding: "10px 0 2px" }}>
          <div style={{ width: 36, height: 4, borderRadius: "var(--radius-full)", background: "var(--gray-200)" }} />
        </div>
        <div style={{ flex: "none", display: "flex", alignItems: "flex-start", gap: 12, padding: "8px 20px 14px" }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: "var(--fs-h3)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-tight)", color: "var(--text-strong)" }}>{title}</div>
            {subtitle && <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-muted)", marginTop: 3 }}>{subtitle}</div>}
          </div>
          <button onClick={onClose} style={{ border: "none", background: "var(--surface-sunken)", width: 32, height: 32, borderRadius: "var(--radius-full)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flex: "none" }}>
            <Icon name="x" size={16} color="var(--text-secondary)" />
          </button>
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: "0 20px 34px" }}>{children}</div>
      </div>
    </div>,
    elRef.current
  );
}

/* ================= pedacinhos compartilhados ================= */
function SchedLabel({ children }) {
  return <div style={{ fontSize: "var(--fs-micro)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: "var(--text-muted)", margin: "18px 0 9px" }}>{children}</div>;
}

function ChipBtn({ on, onClick, children, style = {} }) {
  return (
    <button onClick={onClick} style={{
      border: on ? "1.5px solid var(--brand)" : "1px solid var(--border-default)",
      background: on ? "var(--surface-brand-subtle)" : "var(--surface-card)",
      color: on ? "var(--brand)" : "var(--text-secondary)",
      borderRadius: "var(--radius-full)", padding: "10px 15px", fontSize: "var(--fs-sm)",
      fontWeight: "var(--fw-semibold)", cursor: "pointer", fontFamily: "var(--font-sans)", ...style,
    }}>{children}</button>
  );
}

function DayChips({ value, onChange, days = 14 }) {
  const S = SCH();
  const list = [];
  for (let i = 1; i <= days; i++) {
    const d = S.addDays(S.TODAY, i);
    if (d.getDay() === 0) continue;
    list.push(d);
  }
  return (
    <div style={{ display: "flex", gap: 8, overflowX: "auto", padding: "2px 2px 6px", margin: "0 -2px" }}>
      {list.map((d) => {
        const v = S.iso(d);
        const on = v === value;
        return (
          <button key={v} onClick={() => onChange(v)} style={{
            flex: "none", width: 52, padding: "8px 0 9px", borderRadius: "var(--radius-md)", cursor: "pointer",
            border: on ? "1.5px solid var(--brand)" : "1px solid var(--border-default)",
            background: on ? "var(--surface-brand-subtle)" : "var(--surface-card)",
            display: "flex", flexDirection: "column", alignItems: "center", gap: 1, fontFamily: "var(--font-sans)",
          }}>
            <span style={{ fontSize: 10.5, fontWeight: "var(--fw-semibold)", textTransform: "uppercase", letterSpacing: "var(--ls-wide)", color: on ? "var(--brand)" : "var(--text-faint)" }}>{S.WD[d.getDay()]}</span>
            <span style={{ fontSize: "var(--fs-body-lg)", fontWeight: "var(--fw-bold)", color: on ? "var(--brand)" : "var(--text-strong)" }}>{d.getDate()}</span>
          </button>
        );
      })}
    </div>
  );
}

const SCHED_TIMES = ["8:00 AM", "9:00 AM", "10:00 AM", "11:00 AM", "1:00 PM", "2:00 PM", "3:00 PM", "4:00 PM"];
function TimeChips({ value, onChange }) {
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
      {SCHED_TIMES.map((t) => (
        <ChipBtn key={t} on={t === value} onClick={() => onChange(t)} style={{ fontFamily: "var(--font-mono)", fontSize: "var(--fs-caption)", padding: "9px 12px" }}>{t}</ChipBtn>
      ))}
    </div>
  );
}

function CleanerChips({ value, onChange }) {
  const cleaners = (window.FCData.team || []).filter((m) => m.role === "cleaner");
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
      {cleaners.map((m) => (
        <ChipBtn key={m.id} on={!!value && (m.name === value || m.name.startsWith(value) || value.startsWith(m.name))} onClick={() => onChange(m.name)} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "7px 14px 7px 7px" }}>
          <Avatar name={m.name} size={26} />
          {m.name}
        </ChipBtn>
      ))}
    </div>
  );
}

function SmsToggle({ value, onChange }) {
  return (
    <div onClick={() => onChange(!value)} style={{ display: "flex", alignItems: "center", gap: 12, padding: "13px 14px", borderRadius: "var(--radius-md)", border: "1px solid var(--border-subtle)", background: "var(--surface-sunken)", cursor: "pointer", marginTop: 18 }}>
      <Icon name="message-circle" size={18} color="var(--text-muted)" />
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: "var(--fs-sm)", fontWeight: "var(--fw-semibold)", color: "var(--text-primary)" }}>Avisar cliente por SMS</div>
        <div style={{ fontSize: "var(--fs-micro)", color: "var(--text-muted)", marginTop: 1 }}>A Riley manda a mensagem em inglês</div>
      </div>
      <div style={{ flex: "none", width: 44, height: 26, borderRadius: "var(--radius-full)", background: value ? "var(--brand)" : "var(--gray-200)", position: "relative", transition: "background var(--dur-fast) var(--ease-standard)" }}>
        <div style={{ position: "absolute", top: 3, left: value ? 21 : 3, width: 20, height: 20, borderRadius: "var(--radius-full)", background: "#fff", boxShadow: "var(--shadow-xs)", transition: "left var(--dur-fast) var(--ease-standard)" }} />
      </div>
    </div>
  );
}

function SheetSuccess({ title, sub }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", gap: 10, padding: "26px 12px 30px" }}>
      <div style={{ width: 58, height: 58, borderRadius: "var(--radius-full)", background: "var(--surface-brand-subtle)", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <Icon name="circle-check-big" size={28} color="var(--brand)" />
      </div>
      <div style={{ fontSize: "var(--fs-body-lg)", fontWeight: "var(--fw-bold)", color: "var(--text-strong)" }}>{title}</div>
      {sub && <div style={{ fontSize: "var(--fs-sm)", color: "var(--text-muted)", maxWidth: 280 }}>{sub}</div>}
    </div>
  );
}

/* ================= ENCAIXAR (cliente flexível) ================= */
function FitSheet({ q, onClose, onDone }) {
  const S = SCH();
  const sugg = React.useMemo(() => S.suggestions(q.plan), [q.plan.id]);
  const [pick, setPick] = React.useState(null);        // índice da sugestão
  const [manual, setManual] = React.useState(false);
  const [day, setDay] = React.useState(null);
  const [time, setTime] = React.useState(q.plan.window === "Tarde" ? "1:00 PM" : "9:00 AM");
  const [cleaner, setCleaner] = React.useState(q.plan.cleaner);
  const [sms, setSms] = React.useState(true);
  const [ok, setOk] = React.useState(false);

  const chosen = manual ? (day && { dateIso: day, time }) : (pick != null && sugg[pick]);

  const confirm = () => {
    if (!chosen) return;
    S.confirmFit(q.plan, chosen.dateIso, chosen.time, cleaner, sms);
    setOk(true);
    setTimeout(() => { onDone(); onClose(); }, 1100);
  };

  return (
    <SchedSheet open onClose={onClose} title="Encaixar visita" subtitle={`${q.client.name} · ${S.freqLabel(q.plan)} · sem dia fixo`}>
      {ok ? (
        <SheetSuccess title="Visita encaixada!" sub={`${S.fmt(S.fromISO(chosen.dateIso))} · ${chosen.time}${sms ? " — a Riley avisa o cliente por SMS." : ""}`} />
      ) : (
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: "var(--radius-md)", background: q.overdue ? "var(--danger-bg)" : "var(--warm-bg)" }}>
            <Icon name="calendar-clock" size={18} color={q.overdue ? "var(--danger-600)" : "var(--warm-600)"} />
            <span style={{ fontSize: "var(--fs-sm)", fontWeight: "var(--fw-medium)", color: "var(--text-primary)" }}>
              {q.overdue ? `A ${S.freqLabel(q.plan).toLowerCase()} ${q.label} — encaixe o quanto antes.` : `Próxima limpeza ${q.label} (${S.fmt(q.due)}).`}
            </span>
          </div>

          {!manual && (
            <div>
              <SchedLabel>Sugestões — dias mais vazios</SchedLabel>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {sugg.map((s, i) => {
                  const on = pick === i;
                  return (
                    <button key={s.dateIso} onClick={() => setPick(i)} style={{
                      display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", cursor: "pointer", textAlign: "left",
                      border: on ? "1.5px solid var(--brand)" : "1px solid var(--border-default)",
                      background: on ? "var(--surface-brand-subtle)" : "var(--surface-card)",
                      borderRadius: "var(--radius-md)", fontFamily: "var(--font-sans)",
                    }}>
                      <div style={{ width: 18, height: 18, borderRadius: "var(--radius-full)", border: on ? "5.5px solid var(--brand)" : "1.5px solid var(--border-strong)", boxSizing: "border-box", flex: "none", background: "#fff" }} />
                      <div style={{ flex: 1 }}>
                        <span style={{ fontSize: "var(--fs-body)", fontWeight: "var(--fw-semibold)", color: "var(--text-strong)" }}>{s.date}</span>
                        <span style={{ fontFamily: "var(--font-mono)", fontSize: "var(--fs-sm)", color: "var(--text-secondary)", marginLeft: 8 }}>{s.time}</span>
                      </div>
                      <span style={{ fontSize: "var(--fs-micro)", fontWeight: "var(--fw-semibold)", color: s.note === "agenda livre" ? "var(--success-600)" : "var(--text-muted)" }}>{s.note}</span>
                    </button>
                  );
                })}
              </div>
              <button onClick={() => { setManual(true); setPick(null); }} style={{ border: "none", background: "none", color: "var(--text-link)", fontSize: "var(--fs-sm)", fontWeight: "var(--fw-semibold)", cursor: "pointer", padding: "12px 2px 0", fontFamily: "var(--font-sans)" }}>
            Escolher outro dia e horário →
              </button>
            </div>
          )}

          {manual && (
            <div>
              <SchedLabel>Dia</SchedLabel>
              <DayChips value={day} onChange={setDay} />
              <SchedLabel>Horário</SchedLabel>
              <TimeChips value={time} onChange={setTime} />
              <button onClick={() => { setManual(false); setDay(null); }} style={{ border: "none", background: "none", color: "var(--text-link)", fontSize: "var(--fs-sm)", fontWeight: "var(--fw-semibold)", cursor: "pointer", padding: "12px 2px 0", fontFamily: "var(--font-sans)" }}>
            ← Voltar às sugestões
              </button>
            </div>
          )}

          <SchedLabel>Quem vai</SchedLabel>
          <CleanerChips value={cleaner} onChange={setCleaner} />
          <SmsToggle value={sms} onChange={setSms} />
          <div style={{ marginTop: 18 }}>
            <Button block size="lg" disabled={!chosen} onClick={confirm} iconLeft={<Icon name="calendar-check" size={18} color="#fff" />}>
              {chosen ? `Confirmar — ${S.fmtShort(S.fromISO(chosen.dateIso))} · ${chosen.time}` : "Escolha um horário"}
            </Button>
          </div>
        </div>
      )}
    </SchedSheet>
  );
}

/* ================= REMARCAR (só esta / série) ================= */
function RescheduleSheet({ occ, onClose, onDone }) {
  const S = SCH();
  const hasSeries = !!occ.planId && !!occ.plan;
  const [scope, setScope] = React.useState("only");
  const [day, setDay] = React.useState(null);
  const [time, setTime] = React.useState(occ.time);
  const [sms, setSms] = React.useState(true);
  const [ok, setOk] = React.useState(false);

  const confirm = () => {
    if (!day) return;
    S.reschedule(occ, scope, day, time, sms);
    setOk(true);
    setTimeout(() => { onDone(); onClose(); }, 1100);
  };

  return (
    <SchedSheet open onClose={onClose} title="Remarcar visita" subtitle={`${occ.name} · hoje em ${occ.date} · ${occ.time}`}>
      {ok ? (
        <SheetSuccess
          title={scope === "series" ? "Série remarcada!" : "Visita remarcada!"}
          sub={scope === "series" ? `A recorrência inteira mudou pra ${S.WD[S.fromISO(day).getDay()]} · ${time}.` : `Só esta visita mudou — a série segue no ritmo normal.${sms ? " A Riley avisa o cliente." : ""}`} />
      ) : (
        <div>
          {hasSeries && (
            <div>
              <SchedLabel>O que muda?</SchedLabel>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                {[
                  { v: "only", t: "Só esta visita", s: "A série continua no ritmo normal" },
                  { v: "series", t: "Esta e as próximas", s: `Muda o dia/hora da série ${S.freqLabel(occ.plan).toLowerCase()}` },
                ].map((o) => {
                  const on = scope === o.v;
                  return (
                    <button key={o.v} onClick={() => setScope(o.v)} style={{
                      textAlign: "left", padding: "12px 13px", cursor: "pointer", borderRadius: "var(--radius-md)",
                      border: on ? "1.5px solid var(--brand)" : "1px solid var(--border-default)",
                      background: on ? "var(--surface-brand-subtle)" : "var(--surface-card)", fontFamily: "var(--font-sans)",
                    }}>
                      <div style={{ fontSize: "var(--fs-sm)", fontWeight: "var(--fw-bold)", color: on ? "var(--brand)" : "var(--text-strong)" }}>{o.t}</div>
                      <div style={{ fontSize: "var(--fs-micro)", color: "var(--text-muted)", marginTop: 3, lineHeight: 1.35 }}>{o.s}</div>
                    </button>
                  );
                })}
              </div>
            </div>
          )}
          <SchedLabel>Novo dia</SchedLabel>
          <DayChips value={day} onChange={setDay} />
          <SchedLabel>Novo horário</SchedLabel>
          <TimeChips value={time} onChange={setTime} />
          <SmsToggle value={sms} onChange={setSms} />
          <div style={{ marginTop: 18 }}>
            <Button block size="lg" disabled={!day} onClick={confirm} iconLeft={<Icon name="calendar-check" size={18} color="#fff" />}>
              {scope === "series" ? "Remarcar a série" : "Remarcar esta visita"}
            </Button>
          </div>
        </div>
      )}
    </SchedSheet>
  );
}

/* ================= OCORRÊNCIA (detalhe + ações) ================= */
function OccurrenceSheet({ occ, go, onClose, onReschedule, onChanged }) {
  const S = SCH();
  const [confirmSkip, setConfirmSkip] = React.useState(false);
  const [swapCleaner, setSwapCleaner] = React.useState(false);
  const [cleaner, setCleaner] = React.useState(occ.cleaner);

  const row = (icon, label, sub, onClick, tone) => (
    <button onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 13, width: "100%", padding: "13px 4px", border: "none", borderBottom: "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: tone === "warm" ? "var(--warm-bg)" : "var(--surface-brand-subtle)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
        <Icon name={icon} size={17} color={tone === "warm" ? "var(--warm-600)" : "var(--brand)"} />
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: "var(--fs-body)", fontWeight: "var(--fw-semibold)", color: "var(--text-strong)" }}>{label}</div>
        {sub && <div style={{ fontSize: "var(--fs-micro)", color: "var(--text-muted)", marginTop: 1 }}>{sub}</div>}
      </div>
      <Icon name="chevron-right" size={16} color="var(--text-faint)" />
    </button>
  );

  return (
    <SchedSheet open onClose={onClose} title={occ.name} subtitle={`${occ.service} · ${occ.date} · ${occ.time}`}>
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 6 }}>
        {occ.plan && <Badge tone="brand"><Icon name="repeat" size={11} color="currentColor" style={{ marginRight: 4 }} />{S.freqLabel(occ.plan)}</Badge>}
        {occ.moved && <Badge tone="warning">Fora do ritmo</Badge>}
        {occ.virtual && !occ.moved && <Badge tone="neutral">Projetada</Badge>}
      </div>
      <Card inset style={{ marginBottom: 14 }}>
        <div style={{ padding: "4px 16px" }}>
          <KV k="Cleaner" v={cleaner} />
          <KV k="Endereço" v={occ.address} />
          <KV k="Valor" v={<span style={{ color: "var(--brand)", fontWeight: "var(--fw-bold)" }}>${occ.price}</span>} />
        </div>
      </Card>

      {row("calendar-clock", "Remarcar", occ.plan ? "Só esta visita ou a série inteira" : "Escolher novo dia e horário", onReschedule)}

      {!confirmSkip
        ? row("skip-forward", "Pular esta visita", "Volta no próximo ciclo, no ritmo normal", () => setConfirmSkip(true), "warm")
        : (
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "13px 4px", borderBottom: "1px solid var(--border-subtle)" }}>
            <span style={{ flex: 1, fontSize: "var(--fs-sm)", color: "var(--text-primary)", fontWeight: "var(--fw-medium)" }}>Pular {occ.date}?</span>
            <Button size="sm" variant="secondary" onClick={() => setConfirmSkip(false)}>Voltar</Button>
            <Button size="sm" onClick={() => { SCH().skip(occ); onChanged(); onClose(); }}>Pular</Button>
          </div>
        )}

      {!swapCleaner
        ? row("users", "Trocar cleaner", "Só nesta visita — a série não muda", () => setSwapCleaner(true))
        : (
          <div style={{ padding: "13px 4px", borderBottom: "1px solid var(--border-subtle)" }}>
            <CleanerChips value={cleaner} onChange={(n) => { setCleaner(n); SCH().setCleaner(occ, n); onChanged(); setSwapCleaner(false); }} />
          </div>
        )}

      {row("user-round", "Ver cliente", null, () => { onClose(); go("client", occ.clientId); })}
    </SchedSheet>
  );
}

/* ================= PLANO (criar / editar / pausar / cancelar) ================= */
function PlanSheet({ clientId, onClose, onDone }) {
  const S = SCH();
  const existing = S.planOf(clientId);
  const c = window.FCData.clients.find((x) => x.id === clientId);
  const [f, setF] = React.useState(() => existing
    ? { mode: existing.mode, freq: existing.freq, day: existing.day != null ? existing.day : 1, time: existing.time || "9:00 AM", monthly: existing.monthly || "semana", window: existing.window || "Manhã", cleaner: existing.cleaner }
    : { mode: "fixo", freq: "quinzenal", day: 1, time: "9:00 AM", monthly: "semana", window: "Manhã", cleaner: "Ana Lima" });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const [pausing, setPausing] = React.useState(false);
  const [confirmCancel, setConfirmCancel] = React.useState(false);
  const [ok, setOk] = React.useState(null);

  const finish = (msg, sub) => { setOk({ msg, sub }); setTimeout(() => { onDone(); onClose(); }, 1100); };

  const save = () => {
    S.savePlan(clientId, {
      mode: f.mode, freq: f.freq, monthly: f.freq === "mensal" ? f.monthly : undefined,
      day: f.mode === "fixo" ? f.day : undefined, time: f.mode === "fixo" ? f.time : undefined,
      window: f.window, cleaner: f.cleaner,
      service: existing ? existing.service : (c.prefs && c.prefs.service !== "—" ? c.prefs.service : c.service) || "Regular",
      price: existing ? existing.price : c.avgTicket !== "—" ? c.avgTicket : "150",
      anchor: undefined,
    });
    finish(existing ? "Plano atualizado!" : "Plano criado!", f.mode === "fixo" ? `${({semanal:"Semanal",quinzenal:"Quinzenal",mensal:"Mensal"})[f.freq]} · ${S.WD[f.day]} · ${f.time}` : "Sem dia fixo — você encaixa quando a janela chegar.");
  };

  return (
    <SchedSheet open onClose={onClose} title={existing ? "Plano de limpeza" : "Novo plano de limpeza"} subtitle={c ? c.name : ""}>
      {ok ? <SheetSuccess title={ok.msg} sub={ok.sub} /> : (
        <div>
          {existing && S.isPaused(existing) && (
            <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 13px", borderRadius: "var(--radius-md)", background: "var(--warm-bg)", marginBottom: 4 }}>
              <Icon name="pause" size={16} color="var(--warm-600)" />
              <span style={{ flex: 1, fontSize: "var(--fs-sm)", fontWeight: "var(--fw-medium)", color: "var(--text-primary)" }}>Pausado até {S.fmt(S.fromISO(existing.pausedUntil))}</span>
              <Button size="sm" variant="secondary" onClick={() => { S.resume(existing); onDone(); setPausing(false); setF((p) => ({ ...p })); }}>Retomar</Button>
            </div>
          )}

          <SchedLabel>Frequência</SchedLabel>
          <div style={{ display: "flex", gap: 8 }}>
            {[["semanal", "Semanal"], ["quinzenal", "Quinzenal"], ["mensal", "Mensal"]].map(([v, l]) => (
              <ChipBtn key={v} on={f.freq === v} onClick={() => set("freq", v)}>{l}</ChipBtn>
            ))}
          </div>

          {f.freq === "mensal" && f.mode === "fixo" && (
            <div>
              <SchedLabel>Mensal significa…</SchedLabel>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                {[["semana", "Mesma semana do mês", "ex: toda 2ª quinta"], ["dia", "Mesmo dia do mês", "ex: todo dia 15"]].map(([v, t, s]) => {
                  const on = f.monthly === v;
                  return (
                    <button key={v} onClick={() => set("monthly", v)} style={{ textAlign: "left", padding: "11px 13px", cursor: "pointer", borderRadius: "var(--radius-md)", border: on ? "1.5px solid var(--brand)" : "1px solid var(--border-default)", background: on ? "var(--surface-brand-subtle)" : "var(--surface-card)", fontFamily: "var(--font-sans)" }}>
                      <div style={{ fontSize: "var(--fs-sm)", fontWeight: "var(--fw-bold)", color: on ? "var(--brand)" : "var(--text-strong)" }}>{t}</div>
                      <div style={{ fontSize: "var(--fs-micro)", color: "var(--text-muted)", marginTop: 2 }}>{s}</div>
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          <SchedLabel>Tipo de agendamento</SchedLabel>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
            {[["fixo", "Dia e hora fixos", "Entra na agenda sozinho"], ["flex", "Flexível", "Você encaixa quando a janela chega"]].map(([v, t, s]) => {
              const on = f.mode === v;
              return (
                <button key={v} onClick={() => set("mode", v)} style={{ textAlign: "left", padding: "11px 13px", cursor: "pointer", borderRadius: "var(--radius-md)", border: on ? "1.5px solid var(--brand)" : "1px solid var(--border-default)", background: on ? "var(--surface-brand-subtle)" : "var(--surface-card)", fontFamily: "var(--font-sans)" }}>
                  <div style={{ fontSize: "var(--fs-sm)", fontWeight: "var(--fw-bold)", color: on ? "var(--brand)" : "var(--text-strong)" }}>{t}</div>
                  <div style={{ fontSize: "var(--fs-micro)", color: "var(--text-muted)", marginTop: 2, lineHeight: 1.35 }}>{s}</div>
                </button>
              );
            })}
          </div>

          {f.mode === "fixo" ? (
            <div>
              <SchedLabel>Dia da semana</SchedLabel>
              <div style={{ display: "flex", gap: 6 }}>
                {[1, 2, 3, 4, 5, 6].map((d) => (
                  <ChipBtn key={d} on={f.day === d} onClick={() => set("day", d)} style={{ padding: "9px 0", flex: 1, textAlign: "center" }}>{S.WD[d]}</ChipBtn>
                ))}
              </div>
              <SchedLabel>Horário</SchedLabel>
              <TimeChips value={f.time} onChange={(t) => set("time", t)} />
            </div>
          ) : (
            <div>
              <SchedLabel>Janela preferida</SchedLabel>
              <div style={{ display: "flex", gap: 8 }}>
                {["Manhã", "Tarde"].map((w) => <ChipBtn key={w} on={f.window === w} onClick={() => set("window", w)}>{w}</ChipBtn>)}
              </div>
              <div style={{ display: "flex", gap: 8, alignItems: "flex-start", marginTop: 12, padding: "10px 13px", borderRadius: "var(--radius-md)", background: "var(--surface-sunken)" }}>
                <Icon name="calendar-clock" size={15} color="var(--text-muted)" style={{ marginTop: 1 }} />
                <span style={{ fontSize: "var(--fs-micro)", color: "var(--text-muted)", lineHeight: 1.45 }}>Quando a janela chegar, {c ? c.name.split(" ")[0] : "o cliente"} aparece em <b>Agenda → A encaixar</b> pra você escolher o dia.</span>
              </div>
            </div>
          )}

          <SchedLabel>Cleaner padrão</SchedLabel>
          <CleanerChips value={f.cleaner} onChange={(n) => set("cleaner", n)} />

          <div style={{ marginTop: 20 }}>
            <Button block size="lg" onClick={save} iconLeft={<Icon name="check" size={18} color="#fff" />}>{existing ? "Salvar plano" : "Criar plano"}</Button>
          </div>

          {existing && (
            <div style={{ marginTop: 22, borderTop: "1px solid var(--border-subtle)", paddingTop: 6 }}>
              {!pausing ? (
                <button onClick={() => setPausing(true)} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "12px 2px", border: "none", background: "none", cursor: "pointer", fontFamily: "var(--font-sans)", textAlign: "left" }}>
                  <Icon name="pause" size={17} color="var(--warm-600)" />
                  <span style={{ flex: 1, fontSize: "var(--fs-sm)", fontWeight: "var(--fw-semibold)", color: "var(--text-primary)" }}>Pausar série</span>
                  <span style={{ fontSize: "var(--fs-micro)", color: "var(--text-muted)" }}>férias, viagem…</span>
                </button>
              ) : (
                <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 2px" }}>
                  <span style={{ fontSize: "var(--fs-sm)", color: "var(--text-secondary)", fontWeight: "var(--fw-medium)" }}>Pausar por</span>
                  {[1, 2, 4].map((w) => (
                    <ChipBtn key={w} on={false} onClick={() => { S.pause(existing, w); finish("Série pausada", `Sem visitas até ${S.fmt(S.addDays(S.TODAY, w * 7))}.`); }} style={{ padding: "7px 12px" }}>{w} sem.</ChipBtn>
                  ))}
                  <button onClick={() => setPausing(false)} style={{ border: "none", background: "none", color: "var(--text-muted)", cursor: "pointer", fontSize: "var(--fs-sm)", fontFamily: "var(--font-sans)" }}>✕</button>
                </div>
              )}
              {!confirmCancel ? (
                <button onClick={() => setConfirmCancel(true)} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "12px 2px", border: "none", background: "none", cursor: "pointer", fontFamily: "var(--font-sans)", textAlign: "left" }}>
                  <Icon name="trash-2" size={17} color="var(--danger-500)" />
                  <span style={{ flex: 1, fontSize: "var(--fs-sm)", fontWeight: "var(--fw-semibold)", color: "var(--danger-600)" }}>Cancelar série</span>
                </button>
              ) : (
                <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 2px" }}>
                  <span style={{ flex: 1, fontSize: "var(--fs-sm)", color: "var(--text-primary)", fontWeight: "var(--fw-medium)" }}>As próximas visitas saem da agenda. Certeza?</span>
                  <Button size="sm" variant="secondary" onClick={() => setConfirmCancel(false)}>Voltar</Button>
                  <Button size="sm" variant="danger" onClick={() => { S.cancel(existing); finish("Série cancelada", "O histórico do cliente continua guardado."); }}>Cancelar</Button>
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </SchedSheet>
  );
}

Object.assign(window, { SchedSheet, SchedLabel, ChipBtn, DayChips, TimeChips, CleanerChips, SmsToggle, SheetSuccess, FitSheet, RescheduleSheet, OccurrenceSheet, PlanSheet });
