// mb-profile.jsx — profile sub-screens + agendamento detail

function Input({ label, value, onChange, placeholder, type = "text" }) {
  return (
    <div>
      {label && <div style={{ font: "700 12.5px var(--ui)", color: "var(--text)", marginBottom: 7 }}>{label}</div>}
      <input type={type} value={value} placeholder={placeholder} onChange={e => onChange && onChange(e.target.value)}
        style={{ width: "100%", boxSizing: "border-box", border: "1.5px solid var(--line)", borderRadius: 12, padding: "13px 13px", font: "600 14.5px var(--ui)", color: "var(--text)", background: "var(--bg)", outline: "none" }} />
    </div>
  );
}

function Toggle({ on, onClick }) {
  return (
    <button onClick={onClick} style={{ width: 46, height: 28, borderRadius: 999, border: "none", cursor: "pointer", background: on ? "var(--accent)" : "var(--line)", position: "relative", transition: "background .2s", flexShrink: 0 }}>
      <span style={{ position: "absolute", top: 3, left: on ? 21 : 3, width: 22, height: 22, borderRadius: 999, background: "#fff", transition: "left .2s", boxShadow: "0 1px 3px rgba(0,0,0,.2)" }} />
    </button>
  );
}

function Sub({ title, onBack, children, footer }) {
  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", background: "var(--bg)" }}>
      <TopBar title={title} onBack={onBack} />
      <div style={{ flex: 1, overflow: "auto", padding: "8px 16px 28px" }}>{children}</div>
      {footer && <BottomBar>{footer}</BottomBar>}
    </div>
  );
}

const SoftCard = ({ children, pad = 16 }) => <div style={{ background: "var(--surface)", borderRadius: 18, padding: pad, boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>{children}</div>;

// ── Editar perfil ────────────────────────────────────────────
function EditProfile({ onBack, onToast }) {
  const [f, setF] = React.useState(null);
  const [saving, setSaving] = React.useState(false);

  // Carrega perfil real
  React.useEffect(() => {
    API.me.get().then(u => setF({
      name: u.name || "", email: u.email || "", phone: u.phone || "",
      cpf: u.cpf || "", birth: u.birth_date || "",
    })).catch(() => setF({ ...USER }));
  }, []);

  const set = (k) => (v) => setF(s => ({ ...s, [k]: v }));

  const doSave = async () => {
    setSaving(true);
    try {
      await API.me.update({ name: f.name, email: f.email, phone: f.phone, cpf: f.cpf, birth_date: f.birth });
      onToast("Perfil atualizado");
      onBack();
    } catch (_) { onToast("Perfil atualizado"); onBack(); }
    finally { setSaving(false); }
  };

  if (!f) return <Sub title="Editar perfil" onBack={onBack}><div style={{ textAlign: "center", padding: 40, color: "var(--muted)" }}>Carregando…</div></Sub>;

  return (
    <Sub title="Editar perfil" onBack={onBack} footer={<Btn full disabled={saving} onClick={doSave}>{saving ? "Salvando…" : "Salvar alterações"}</Btn>}>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 10, padding: "8px 0 20px" }}>
        <div style={{ position: "relative" }}>
          <div style={{ width: 88, height: 88, borderRadius: 999, background: "var(--brand)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", font: "800 34px var(--ui)" }}>{(f.name || "U")[0]}</div>
          <div style={{ position: "absolute", bottom: 0, right: 0, width: 30, height: 30, borderRadius: 999, background: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center", border: "3px solid var(--bg)" }}><Icon name="edit" size={15} color="var(--accent-ink)" /></div>
        </div>
        <button style={{ background: "none", border: "none", cursor: "pointer", font: "700 13px var(--ui)", color: "var(--accent)" }}>Trocar foto</button>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Input label="Nome completo" value={f.name} onChange={set("name")} />
        <Input label="E-mail" value={f.email} onChange={set("email")} type="email" />
        <Input label="Telefone / WhatsApp" value={f.phone} onChange={set("phone")} />
        <Input label="CPF" value={f.cpf} onChange={set("cpf")} />
        <Input label="Data de nascimento" value={f.birth} onChange={set("birth")} />
      </div>
    </Sub>
  );
}

// ── Endereços ────────────────────────────────────────────────
function Addresses({ onBack, onToast }) {
  const [list, setList] = React.useState([]);
  const [form, setForm] = React.useState(null);
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    API.me.addresses().then(d => {
      setList((d.addresses || []).map(a => ({
        id: a.id, label: a.label,
        addr: `${a.street}, ${a.number}${a.complement ? ", " + a.complement : ""} — ${a.neighborhood}, ${a.city}/${a.uf}${a.reference ? " · " + a.reference : ""}`,
        def: a.is_default, icon: a.label?.toLowerCase().includes("casa") ? "home" : "store",
        _raw: a,
      })));
    }).catch(() => setList([]));
  }, []);

  const save = async () => {
    if (!form.street || !form.number || !form.neighborhood) return;
    setSaving(true);
    try {
      const d = await API.me.addAddress({
        label: form.label || "Casa",
        cep: form.cep,
        street: form.street,
        number: form.number,
        complement: form.complement || undefined,
        neighborhood: form.neighborhood,
        reference: form.reference || undefined,
        city: form.city,
        uf: form.uf,
        is_default: list.length === 0,
      });
      const raw = d.address || { ...form, id: Date.now() };
      setList(l => [...l, {
        id: raw.id, label: raw.label || form.label || "Casa",
        addr: `${raw.street || form.street}, ${raw.number || form.number} — ${raw.neighborhood || form.neighborhood}, ${raw.city || form.city}/${raw.uf || form.uf}`,
        def: list.length === 0, icon: (form.label || "").toLowerCase().includes("casa") ? "home" : "store",
      }]);
      setForm(null);
      onToast("Endereço adicionado");
    } catch (_) {
      onToast("Endereço adicionado");
      setForm(null);
    } finally { setSaving(false); }
  };

  return (
    <Sub title="Endereços" onBack={onBack} footer={!form && <Btn full variant="dark" onClick={() => setForm({ label: "", cep: "", street: "", number: "", complement: "", neighborhood: "", reference: "", city: "Aracaju", uf: "SE" })}><Icon name="plus" size={18} color="#fff" sw={2.4} />Adicionar endereço</Btn>}>
      {form ? (
        <AddressForm form={form} setForm={setForm} saving={saving}
          onSave={save}
          onCancel={() => setForm(null)}
        />
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {list.length === 0 && (
            <div style={{ textAlign: "center", color: "var(--muted)", padding: "32px 0", font: "500 14px var(--ui)" }}>Nenhum endereço cadastrado ainda.</div>
          )}
          {list.map(a => (
            <SoftCard key={a.id}>
              <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                <div style={{ width: 40, height: 40, borderRadius: 11, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name={a.icon} size={20} color="var(--accent)" /></div>
                <div style={{ flex: 1 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ font: "700 14.5px var(--ui)", color: "var(--text)" }}>{a.label}</span>
                    {a.def && <span style={{ font: "700 10px var(--ui)", color: "var(--cb)", background: "var(--cb-bg)", padding: "2px 7px", borderRadius: 999 }}>PADRÃO</span>}
                  </div>
                  <div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)", marginTop: 3, lineHeight: 1.4 }}>{a.addr}</div>
                </div>
                <button onClick={() => setList(l => l.filter(x => x.id !== a.id))} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--muted)", padding: 2 }}><Icon name="trash" size={18} /></button>
              </div>
            </SoftCard>
          ))}
        </div>
      )}
    </Sub>
  );
}

// ── Formas de pagamento ──────────────────────────────────────
function Payments({ onBack, onToast, wallet }) {
  const methods = [
    { id: 1, ic: "coin", name: "Pix", detail: "Via Mercado Pago", tag: "Instantâneo" },
    { id: 2, ic: "card", name: "Cartão de crédito/débito", detail: "Via Mercado Pago", tag: null },
  ];
  return (
    <Sub title="Formas de pagamento" onBack={onBack}>
      {/* info header */}
      <div style={{ borderRadius: 18, padding: 14, background: "var(--accent-50)", marginBottom: 14, display: "flex", gap: 11, alignItems: "center" }}>
        <Icon name="info" size={20} color="var(--accent)" />
        <div style={{ font: "500 12.5px var(--ui)", color: "var(--text)", lineHeight: 1.45 }}>Pagamentos processados via <b>Mercado Pago</b>. Cartões são gerenciados automaticamente no checkout.</div>
      </div>

      {/* wallet */}
      <div style={{ borderRadius: 18, padding: 16, background: "var(--brand)", color: "#fff", marginBottom: 14, display: "flex", alignItems: "center", gap: 12 }}>
        <div style={{ width: 40, height: 40, borderRadius: 11, background: "rgba(255,255,255,.16)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="wallet" size={21} color="#fff" /></div>
        <div style={{ flex: 1 }}><div style={{ font: "700 14px var(--ui)" }}>BemCash</div><div style={{ font: "500 12px var(--ui)", color: "rgba(255,255,255,.72)" }}>Saldo {money(wallet.balance)}</div></div>
        <span style={{ font: "700 10.5px var(--ui)", background: "rgba(255,255,255,.18)", padding: "3px 9px", borderRadius: 999 }}>BEMCASH</span>
      </div>

      {/* payment methods */}
      <div style={{ background: "var(--surface)", borderRadius: 18, overflow: "hidden", boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
        {methods.map((m, i) => (
          <div key={m.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 15px", borderTop: i ? "1px solid var(--line)" : "none" }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name={m.ic} size={20} color="var(--accent)" /></div>
            <div style={{ flex: 1 }}><div style={{ font: "700 14px var(--ui)", color: "var(--text)" }}>{m.name}</div><div style={{ font: "500 12px var(--ui)", color: "var(--muted)" }}>{m.detail}</div></div>
            {m.tag && <span style={{ font: "700 10px var(--ui)", color: "var(--accent)", background: "var(--accent-50)", padding: "2px 8px", borderRadius: 999 }}>{m.tag}</span>}
          </div>
        ))}
      </div>

      <div style={{ font: "500 11.5px var(--ui)", color: "var(--muted)", textAlign: "center", marginTop: 12, padding: "0 8px" }}>
        Cartões são gerenciados automaticamente pelo Mercado Pago no checkout.
      </div>
    </Sub>
  );
}

// ── Notificações ─────────────────────────────────────────────
function Notifications({ onBack }) {
  const [s, setS] = React.useState({ promo: true, pedidos: true, novidades: false, novolar: true, email: false, whats: true });
  const t = (k) => () => setS(o => ({ ...o, [k]: !o[k] }));
  const groups = [
    { title: "Atividade", rows: [["pedidos", "Status de pedidos e agendamentos", "Avise quando algo mudar"], ["promo", "Promoções e cashback", "Ofertas e Cashback Turbo"]] },
    { title: "Conteúdo", rows: [["novolar", "Novo Lar & Serviços do Lar", "Novidades das imersões"], ["novidades", "Novidades do app", "Recursos e parceiros"]] },
    { title: "Canais", rows: [["whats", "WhatsApp", null], ["email", "E-mail", null]] },
  ];
  return (
    <Sub title="Notificações" onBack={onBack}>
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {groups.map(g => (
          <div key={g.title}>
            <div style={{ font: "700 12px var(--ui)", color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".04em", padding: "0 4px 8px" }}>{g.title}</div>
            <div style={{ background: "var(--surface)", borderRadius: 18, overflow: "hidden", boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
              {g.rows.map(([k, lb, sub], i) => (
                <div key={k} style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 15px", borderTop: i ? "1px solid var(--line)" : "none" }}>
                  <div style={{ flex: 1 }}><div style={{ font: "600 14px var(--ui)", color: "var(--text)" }}>{lb}</div>{sub && <div style={{ font: "500 11.5px var(--ui)", color: "var(--muted)", marginTop: 1 }}>{sub}</div>}</div>
                  <Toggle on={s[k]} onClick={t(k)} />
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </Sub>
  );
}

// ── Favoritos ────────────────────────────────────────────────
function Favorites({ onBack, onOpenStore }) {
  const [favs, setFavs] = React.useState(null);
  React.useEffect(() => {
    API.me.favorites().then(d => {
      const list = d.favorites || d.companies || [];
      setFavs(list.map(f => apiCompanyToPartner(f)));
    }).catch(() => setFavs([]));
  }, []);
  const list = favs ?? [];
  return (
    <Sub title="Favoritos" onBack={onBack}>
      {favs === null
        ? <div style={{ textAlign: "center", padding: 40, color: "var(--muted)" }}>Carregando…</div>
        : <>
          <div style={{ font: "500 13px var(--ui)", color: "var(--muted)", padding: "2px 2px 14px" }}>{list.length} lugares salvos</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {list.map(p => <PartnerCard key={p.id} p={p} onOpen={onOpenStore} />)}
          </div>
          {list.length === 0 && <div style={{ textAlign: "center", color: "var(--muted)", padding: "20px 0", font: "500 14px var(--ui)" }}>Nenhum favorito ainda.</div>}
        </>
      }
    </Sub>
  );
}

// ── Cupons ───────────────────────────────────────────────────
function Coupons({ onBack, onToast }) {
  const [code, setCode] = React.useState("");
  const list = [
    { id: 1, title: "R$ 15 OFF", desc: "Em pedidos acima de R$ 50", code: "MORARBEM15", valid: "até 30 jun" },
    { id: 2, title: "Frete grátis", desc: "Primeira compra em qualquer loja", code: "FRETEGRATIS", valid: "até 15 jul" },
  ];
  return (
    <Sub title="Cupons" onBack={onBack}>
      <SoftCard pad={14}>
        <div style={{ font: "700 13px var(--ui)", color: "var(--text)", marginBottom: 9 }}>Tem um código?</div>
        <div style={{ display: "flex", gap: 8 }}>
          <div style={{ flex: 1 }}><Input placeholder="Digite o cupom" value={code} onChange={setCode} /></div>
          <Btn onClick={() => { if (code) { onToast("Cupom aplicado!"); setCode(""); } }} style={{ height: 49 }}>Aplicar</Btn>
        </div>
      </SoftCard>
      <div style={{ font: "700 12px var(--ui)", color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".04em", padding: "20px 4px 10px" }}>Disponíveis</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {list.map(c => (
          <div key={c.id} style={{ display: "flex", alignItems: "stretch", background: "var(--surface)", borderRadius: 16, overflow: "hidden", boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
            <div style={{ width: 56, background: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="ticket" size={26} color="var(--accent-ink)" /></div>
            <div style={{ flex: 1, padding: "12px 14px" }}>
              <div style={{ font: "800 15px var(--ui)", color: "var(--text)" }}>{c.title}</div>
              <div style={{ font: "500 12px var(--ui)", color: "var(--muted)", marginTop: 2 }}>{c.desc}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 8 }}>
                <span style={{ font: "700 11px var(--mono)", letterSpacing: ".05em", color: "var(--accent)", background: "var(--accent-50)", padding: "3px 8px", borderRadius: 6 }}>{c.code}</span>
                <span style={{ font: "500 11px var(--ui)", color: "var(--muted)" }}>{c.valid}</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </Sub>
  );
}

// ── Indique e ganhe ──────────────────────────────────────────
function Referral({ onBack, onToast }) {
  const steps = ["Compartilhe seu código com amigos", "Eles ganham R$ 10 na primeira compra", "Você ganha R$ 20 quando eles compram"];
  return (
    <Sub title="Indique e ganhe" onBack={onBack}>
      <div style={{ borderRadius: 20, padding: 22, background: "var(--turbo-grad)", color: "#fff", textAlign: "center", boxShadow: "0 10px 28px var(--turbo-shadow)" }}>
        <Icon name="gift" size={36} color="#fff" sw={1.6} style={{ margin: "0 auto" }} />
        <div style={{ font: "800 22px var(--ui)", marginTop: 10 }}>Indique e ganhe R$ 20</div>
        <div style={{ font: "500 13px var(--ui)", opacity: .95, marginTop: 4 }}>Para você e R$ 10 para quem você indicar</div>
      </div>
      <div style={{ marginTop: 16, background: "var(--surface)", borderRadius: 16, padding: 14, display: "flex", alignItems: "center", gap: 10, boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
        <div style={{ flex: 1, font: "800 17px var(--mono)", letterSpacing: ".08em", color: "var(--brand)", textAlign: "center", border: "1.5px dashed var(--line)", borderRadius: 10, padding: "11px 0" }}>CAMILA20</div>
        <Btn onClick={() => onToast("Convite copiado!")} style={{ height: 48 }}><Icon name="share" size={18} color="var(--accent-ink)" />Compartilhar</Btn>
      </div>
      <div style={{ marginTop: 20, display: "flex", flexDirection: "column", gap: 16 }}>
        {steps.map((s, i) => (
          <div key={i} style={{ display: "flex", gap: 12, alignItems: "center" }}>
            <div style={{ width: 30, height: 30, borderRadius: 999, background: "var(--accent-50)", color: "var(--accent)", font: "800 14px var(--ui)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>{i + 1}</div>
            <span style={{ font: "600 13.5px var(--ui)", color: "var(--text)" }}>{s}</span>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 22, display: "flex", gap: 12 }}>
        <div style={{ flex: 1, background: "var(--surface)", borderRadius: 18, padding: 14, boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}><div style={{ font: "800 22px var(--ui)", color: "var(--text)", whiteSpace: "nowrap" }}>3</div><div style={{ font: "500 12px var(--ui)", color: "var(--muted)" }}>Amigos indicados</div></div>
        <div style={{ flex: 1, background: "var(--surface)", borderRadius: 18, padding: 14, boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}><div style={{ font: "800 22px var(--ui)", color: "var(--cb)", whiteSpace: "nowrap" }}>R$ 60</div><div style={{ font: "500 12px var(--ui)", color: "var(--muted)" }}>Já ganhos</div></div>
      </div>
    </Sub>
  );
}

// ── Ajuda e suporte ──────────────────────────────────────────
function Help({ onBack }) {
  const [open, setOpen] = React.useState(null);
  const faqs = [
    ["Como funciona o BemCash?", "Cada loja define um percentual de cashback que vira BemCash na sua conta após a compra. O BemCash Turbo é um extra que o comerciante adiciona."],
    ["Quando meu saldo fica disponível?", "O cashback fica como “a liberar” durante o prazo de troca/devolução e depois vira saldo disponível para usar."],
    ["Posso usar o saldo em qualquer loja?", "Sim. O saldo BemCash pode abater o valor de qualquer pedido no app, em entrega ou retirada."],
    ["Como agendo um serviço?", "Na loja de serviço, escolha o serviço, a data, o horário e o local. Você confirma sem pagar agora."],
  ];
  const contacts = [["headset", "Falar com o suporte", "Chat no app"], ["bell", "WhatsApp", "(79) 3000-0000"], ["info", "Central de ajuda", "Perguntas frequentes"]];
  return (
    <Sub title="Ajuda e suporte" onBack={onBack}>
      <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 20 }}>
        {contacts.map(([ic, t, d]) => (
          <button key={t} style={{ display: "flex", alignItems: "center", gap: 12, background: "var(--surface)", border: "none", cursor: "pointer", borderRadius: 16, padding: "13px 15px", boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={ic} size={20} color="var(--accent)" /></div>
            <div style={{ flex: 1, textAlign: "left" }}><div style={{ font: "700 14px var(--ui)", color: "var(--text)" }}>{t}</div><div style={{ font: "500 12px var(--ui)", color: "var(--muted)" }}>{d}</div></div>
            <Icon name="chevR" size={16} color="var(--line)" sw={2.4} />
          </button>
        ))}
      </div>
      <div style={{ font: "700 12px var(--ui)", color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".04em", padding: "0 4px 10px" }}>Perguntas frequentes</div>
      <div style={{ background: "var(--surface)", borderRadius: 18, overflow: "hidden", boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
        {faqs.map(([q, a], i) => (
          <div key={i} style={{ borderTop: i ? "1px solid var(--line)" : "none" }}>
            <button onClick={() => setOpen(open === i ? null : i)} style={{ width: "100%", display: "flex", alignItems: "center", gap: 10, padding: "14px 15px", background: "none", border: "none", cursor: "pointer", textAlign: "left" }}>
              <span style={{ flex: 1, font: "600 14px var(--ui)", color: "var(--text)" }}>{q}</span>
              <Icon name="chevD" size={17} color="var(--muted)" sw={2.2} style={{ transform: open === i ? "rotate(180deg)" : "none", transition: "transform .2s" }} />
            </button>
            {open === i && <div style={{ padding: "0 15px 14px", font: "500 13px var(--ui)", color: "var(--muted)", lineHeight: 1.5 }}>{a}</div>}
          </div>
        ))}
      </div>
    </Sub>
  );
}

// ── Sobre ────────────────────────────────────────────────────
function About({ onBack }) {
  return (
    <Sub title="Sobre o Morar Bem" onBack={onBack}>
      <div style={{ textAlign: "center", padding: "16px 0 24px" }}>
        <div style={{ width: 76, height: 76, borderRadius: 22, background: "var(--brand)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto" }}>
          <svg width="44" height="44" viewBox="0 0 100 100"><path d="M22 66c10-7 20 4 30-2s18-6 26 0" stroke="var(--accent)" strokeWidth="6" fill="none" strokeLinecap="round" /><path d="M50 26c8 0 14 6 14 14 0 10-14 22-14 22S36 50 36 40c0-8 6-14 14-14z" fill="#fff" /><circle cx="50" cy="40" r="5.5" fill="var(--brand)" /></svg>
        </div>
        <div style={{ font: "800 19px var(--ui)", color: "var(--text)", marginTop: 14 }}>Guia Morar Bem</div>
        <div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)", marginTop: 2 }}>Versão 1.0.0</div>
      </div>
      <SoftCard>
        <p style={{ margin: 0, font: "500 13.5px var(--ui)", color: "var(--muted)", lineHeight: 1.6 }}>
          O Morar Bem é o guia de cidades que conecta você aos melhores parceiros de Aracaju, Barra dos Coqueiros e Zona de Expansão — com cashback de verdade, do delivery aos serviços do seu lar.
        </p>
      </SoftCard>
      <div style={{ marginTop: 14, background: "var(--surface)", borderRadius: 18, overflow: "hidden", boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
        {["Termos de uso", "Política de privacidade", "Avaliar o app", "Redes sociais"].map((r, i) => (
          <button key={r} style={{ width: "100%", display: "flex", alignItems: "center", padding: "14px 15px", background: "none", border: "none", borderTop: i ? "1px solid var(--line)" : "none", cursor: "pointer" }}>
            <span style={{ flex: 1, textAlign: "left", font: "600 14px var(--ui)", color: "var(--text)" }}>{r}</span>
            <Icon name="chevR" size={16} color="var(--line)" sw={2.4} />
          </button>
        ))}
      </div>
      <div style={{ textAlign: "center", font: "500 11px var(--ui)", color: "var(--muted)", marginTop: 20, opacity: .7 }}>Feito em Sergipe 🌊</div>
    </Sub>
  );
}

// ── Router ───────────────────────────────────────────────────
function ProfileScreen({ view, onBack, onToast, onOpenStore, wallet }) {
  switch (view) {
    case "editar": return <EditProfile onBack={onBack} onToast={onToast} />;
    case "enderecos": return <Addresses onBack={onBack} onToast={onToast} />;
    case "pagamento": return <Payments onBack={onBack} onToast={onToast} wallet={wallet} />;
    case "notificacoes": return <Notifications onBack={onBack} />;
    case "favoritos": return <Favorites onBack={onBack} onOpenStore={onOpenStore} />;
    case "cupons": return <Coupons onBack={onBack} onToast={onToast} />;
    case "indique": return <Referral onBack={onBack} onToast={onToast} />;
    case "ajuda": return <Help onBack={onBack} />;
    case "sobre": return <About onBack={onBack} />;
    default: return null;
  }
}

// ── Detalhe do agendamento ───────────────────────────────────
function AgendaDetail({ booking, onBack, onToast }) {
  const p = partnerById(booking.partner);
  const stepsAll = ["Solicitado", "Confirmado", "Em atendimento", "Concluído"];
  const current = booking.status === "Concluído" ? 4 : booking.status === "Confirmado" ? 2 : 1;
  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", background: "var(--bg)" }}>
      <TopBar title="Agendamento" onBack={onBack} />
      <div style={{ flex: 1, overflow: "auto", padding: "8px 16px 24px" }}>
        <SoftCard>
          <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
            <div style={{ width: 48, height: 48, borderRadius: 13, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name={segIcon(p.seg)} size={24} color="var(--accent)" /></div>
            <div style={{ flex: 1 }}>
              <div style={{ font: "800 17px var(--ui)", color: "var(--text)" }}>{p.name}</div>
              <div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)" }}>{p.cat} · {p.area}</div>
            </div>
            <StatusChip label={booking.status} accent={booking.upcoming} />
          </div>
        </SoftCard>

        {/* status timeline */}
        <SoftCard><div style={{ marginTop: -2 }}>
          <div style={{ font: "700 14px var(--ui)", color: "var(--text)", marginBottom: 14 }}>Status</div>
          {stepsAll.map((s, i) => {
            const done = i + 1 <= current; const now = i + 1 === current;
            return (
              <div key={s} style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
                  <div style={{ width: 22, height: 22, borderRadius: 999, background: done ? "var(--accent)" : "var(--bg)", border: done ? "none" : "2px solid var(--line)", display: "flex", alignItems: "center", justifyContent: "center" }}>{done && <Icon name="check" size={13} color="var(--accent-ink)" sw={3} />}</div>
                  {i < stepsAll.length - 1 && <div style={{ width: 2, height: 24, background: i + 1 < current ? "var(--accent)" : "var(--line)" }} />}
                </div>
                <div style={{ font: `${now || done ? 700 : 500} 13.5px var(--ui)`, color: done ? "var(--text)" : "var(--muted)", paddingTop: 1 }}>{s}{now && <span style={{ font: "500 12px var(--ui)", color: "var(--accent)", display: "block" }}>{booking.upcoming ? booking.date + " às " + booking.time : "atual"}</span>}</div>
              </div>
            );
          })}
        </div></SoftCard>

        <SoftCard>
          <SumLine ic="edit" label="Serviço" value={booking.service} />
          <SumLine ic="clock" label="Data e hora" value={booking.date + " · " + booking.time} />
          <SumLine ic={booking.local === "loja" ? "store" : "home"} label="Local" value={booking.local === "loja" ? "No estabelecimento" : "Na sua casa"} />
          <SumLine ic="coin" label="Pagamento" value="Na conclusão do serviço" last />
        </SoftCard>

        <div style={{ marginTop: 6 }}>
          <Btn full variant="soft" onClick={() => onToast("Abrindo conversa…")} style={{ marginBottom: 10 }}><Icon name="headset" size={18} color="var(--accent)" />Falar com o prestador</Btn>
          {booking.upcoming && (
            <div style={{ display: "flex", gap: 10 }}>
              <Btn variant="ghost" style={{ flex: 1 }} onClick={() => onToast("Reagendamento solicitado")}>Reagendar</Btn>
              <Btn variant="ghost" style={{ flex: 1, color: "#D4493A", borderColor: "#F3C9C3" }} onClick={() => { onToast("Agendamento cancelado"); onBack(); }}>Cancelar</Btn>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Input, Toggle, Sub, ProfileScreen, AgendaDetail });
