// mb-account.jsx — Carteira, Minhas Compras, Perfil

function EmBreveOverlay({ icon, title, text }) {
  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 10, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", background: "var(--bg)", padding: "0 32px", textAlign: "center" }}>
      <div style={{ width: 72, height: 72, borderRadius: 20, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 20 }}>
        <Icon name={icon} size={32} color="var(--accent)" />
      </div>
      <div style={{ font: "800 21px var(--ui)", color: "var(--text)", marginBottom: 10, lineHeight: 1.25 }}>{title}</div>
      <div style={{ font: "500 14px var(--ui)", color: "var(--muted)", lineHeight: 1.6, maxWidth: 300 }}>{text}</div>
      <div style={{ marginTop: 24, display: "inline-flex", alignItems: "center", gap: 8, background: "var(--accent)", color: "#fff", borderRadius: 999, padding: "9px 20px", font: "700 13px var(--ui)" }}>
        <Icon name="clock" size={15} color="#fff" />
        Em breve
      </div>
    </div>
  );
}

function CarteiraScreen({ wallet, onOpenCashback, featureEnabled }) {
  if (!featureEnabled) return (
    <div style={{ position: "absolute", inset: 0, paddingBottom: TAB_H2 }}>
      <EmBreveOverlay icon="coin" title="Sua carteira digital está chegando"
        text="Em breve você poderá receber e usar seu cashback BemCash diretamente aqui, na palma da sua mão." />
    </div>
  );
  return (
    <div style={{ position: "absolute", inset: 0, overflow: "auto", paddingBottom: TAB_H2 }}>
      <div style={{ padding: "28px 16px 14px" }}>
        <h1 style={{ margin: 0, font: "800 26px var(--ui)", color: "var(--text)" }}>BemCash</h1>
      </div>

      {/* balance card */}
      <div style={{ margin: "0 16px", borderRadius: 22, padding: 22, background: "var(--brand)", color: "#fff", position: "relative", overflow: "hidden" }}>
        <div style={{ font: "600 13px var(--ui)", color: "rgba(255,255,255,.72)" }}>Saldo disponível</div>
        <div style={{ font: "900 40px var(--ui)", marginTop: 2, letterSpacing: "-.02em" }}>{money(wallet.balance)}</div>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 6, marginTop: 10, background: "rgba(255,255,255,.14)", borderRadius: 999, padding: "5px 11px", font: "600 12px var(--ui)" }}>
          <Icon name="clock" size={14} color="#fff" sw={2} />{money(wallet.pending)} a liberar
        </div>
        <Icon name="coin" size={150} color="rgba(255,255,255,.08)" sw={1} style={{ position: "absolute", right: -24, bottom: -34 }} />
      </div>

      {/* actions */}
      <div style={{ display: "flex", gap: 10, padding: "14px 16px 4px" }}>
        {[["coin", "Usar saldo"], ["receipt", "Extrato"], ["headset", "Ajuda"]].map(([ic, lb]) => (
          <button key={lb} style={{ flex: 1, background: "var(--surface)", border: "none", cursor: "pointer", borderRadius: 16, padding: "14px 8px", display: "flex", flexDirection: "column", alignItems: "center", gap: 7, boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
            <Icon name={ic} size={22} color="var(--accent)" /><span style={{ font: "600 12px var(--ui)", color: "var(--text)" }}>{lb}</span>
          </button>
        ))}
      </div>

      {/* how cashback works */}
      <button onClick={onOpenCashback} style={{ width: "calc(100% - 32px)", margin: "12px 16px 0", textAlign: "left", cursor: "pointer", border: "none", borderRadius: 18, padding: "15px 16px", background: "var(--cb-bg)", display: "flex", alignItems: "center", gap: 12 }}>
        <div style={{ width: 42, height: 42, borderRadius: 12, background: "var(--cb)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="bolt" size={22} color="#fff" fill="#fff" sw={1.5} /></div>
        <div style={{ flex: 1 }}>
          <div style={{ font: "800 14px var(--ui)", color: "var(--cb-ink)" }}>Como funciona o BemCash?</div>
          <div style={{ font: "500 12px var(--ui)", color: "var(--cb-ink)", opacity: .8 }}>BemCash, Turbo e onde usar seu saldo</div>
        </div>
        <Icon name="chevR" size={18} color="var(--cb)" sw={2.2} />
      </button>

      {/* movements */}
      <div style={{ padding: "22px 16px 8px", font: "800 16px var(--ui)", color: "var(--text)" }}>Movimentações</div>
      <div style={{ margin: "0 16px", background: "var(--surface)", borderRadius: 18, overflow: "hidden", boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
        {wallet.movements.map((m, i) => (
          <div key={m.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "13px 15px", borderTop: i ? "1px solid var(--line)" : "none" }}>
            <div style={{ width: 38, height: 38, borderRadius: 11, flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", background: m.kind === "out" ? "var(--bg)" : m.turbo ? "var(--turbo-grad)" : "var(--cb-bg)" }}>
              <Icon name={m.kind === "out" ? "bag" : m.turbo ? "bolt" : "coin"} size={19} sw={1.7} color={m.kind === "out" ? "var(--muted)" : m.turbo ? "#fff" : "var(--cb)"} fill={m.turbo ? "#fff" : "none"} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ font: "600 13.5px var(--ui)", color: "var(--text)" }}>{m.label}</div>
              <div style={{ font: "500 11.5px var(--ui)", color: "var(--muted)" }}>{m.date}</div>
            </div>
            <span style={{ font: "800 14.5px var(--ui)", color: m.value < 0 ? "var(--text)" : "var(--cb)" }}>{m.value < 0 ? "− " : "+"}{money(Math.abs(m.value))}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// Cashback explainer (sheet content)
function CashbackInfo() {
  const items = [
    { ic: "coin", t: "BemCash", d: "Cada loja define um percentual de cashback nos produtos. Ao comprar, esse valor vira BemCash na sua conta." },
    { ic: "bolt", t: "Cashback Turbo", d: "Um percentual extra que o comerciante turbina para destacar a loja. Esse adicional sai da carteira digital exclusiva do comerciante." },
    { ic: "wallet", t: "Onde usar", d: "Use o saldo acumulado para abater o valor de qualquer pedido dentro do app, em entrega ou retirada." },
    { ic: "clock", t: "Liberação", d: "O cashback fica como “a liberar” durante o prazo de troca/devolução e depois vira saldo disponível." },
  ];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{ borderRadius: 18, padding: 18, background: "var(--turbo-grad)", color: "#fff", textAlign: "center" }}>
        <Icon name="coin" size={34} color="#fff" sw={1.6} style={{ margin: "0 auto" }} />
        <div style={{ font: "800 17px var(--ui)", marginTop: 8 }}>Compre e receba de volta</div>
        <div style={{ font: "500 13px var(--ui)", opacity: .95, marginTop: 3 }}>BemCash + Turbo direto na sua conta</div>
      </div>
      {items.map(it => (
        <div key={it.t} style={{ display: "flex", gap: 13 }}>
          <div style={{ width: 42, height: 42, borderRadius: 12, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon name={it.ic} size={21} color="var(--accent)" fill={it.ic === "bolt" ? "var(--accent)" : "none"} sw={1.7} />
          </div>
          <div>
            <div style={{ font: "700 14.5px var(--ui)", color: "var(--text)" }}>{it.t}</div>
            <div style={{ font: "500 13px var(--ui)", color: "var(--muted)", lineHeight: 1.5, marginTop: 2 }}>{it.d}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Minhas Compras ───────────────────────────────────────────
function StatusChip({ label, accent, warn }) {
  const bg    = warn ? "#FEF3E2" : accent ? "var(--accent-50)" : "var(--bg)";
  const color = warn ? "#B5751A" : accent ? "var(--accent)"    : "var(--muted)";
  return <span style={{ font: "600 11.5px var(--ui)", color, background: bg, padding: "3px 9px", borderRadius: 999, whiteSpace: "nowrap" }}>{label}</span>;
}

const ORDER_STEPS = [
  { status: "aguardando_pagamento", label: "Aguardando pagamento", icon: "coin" },
  { status: "pendente",             label: "Pedido recebido",      icon: "receipt" },
  { status: "em_preparo",           label: "Em preparo",           icon: "bag" },
  { status: "saiu_para_entrega",    label: "Saiu para entrega",    icon: "bike" },
  { status: "entregue",             label: "Entregue",             icon: "check" },
  { status: "concluido",            label: "Finalizado",           icon: "coin" },
];
const APPT_STEPS = [
  { status: "solicitado",     label: "Agendamento recebido", icon: "clock" },
  { status: "confirmado",     label: "Confirmado",           icon: "check" },
  { status: "em_atendimento", label: "Em atendimento",       icon: "health" },
  { status: "concluido",      label: "Finalizado",           icon: "coin" },
];

function StatusTimeline({ steps, currentStatus }) {
  const currentIdx = steps.findIndex(s => s.status === currentStatus);
  return (
    <div style={{ margin: "16px 0" }}>
      {steps.map((step, i) => {
        const done = i < currentIdx;
        const active = i === currentIdx;
        const future = i > currentIdx;
        return (
          <div key={step.status} style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
              <div style={{
                width: 28, height: 28, borderRadius: 999,
                background: done ? "var(--accent)" : active ? "var(--brand)" : "var(--bg)",
                border: future ? "2px solid var(--line)" : "none",
                display: "flex", alignItems: "center", justifyContent: "center",
                flexShrink: 0,
              }}>
                <Icon name={step.icon} size={14} color={done || active ? "#fff" : "var(--line)"} sw={2} />
              </div>
              {i < steps.length - 1 && <div style={{ width: 2, height: 24, background: done ? "var(--accent)" : "var(--line)", opacity: future ? .4 : 1 }} />}
            </div>
            <div style={{ paddingTop: 3, paddingBottom: i < steps.length - 1 ? 0 : 0 }}>
              <div style={{ font: `${active ? 700 : 500} 13.5px var(--ui)`, color: future ? "var(--muted)" : "var(--text)" }}>{step.label}</div>
              {active && <div style={{ font: "500 11.5px var(--ui)", color: "var(--accent)", marginTop: 1 }}>agora</div>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function OrderDetail({ order, onBack, onReview, onReorder }) {
  const raw = order._raw || {};
  const shortId = (raw.id || order.id || "").slice(0, 8);
  const p = partnerById(order.partner) || { name: raw.company_name || "Parceiro", seg: "comer" };
  const canReview = raw.status === "concluido" || raw.status === "entregue";
  const awaitingPayment = raw.status === "aguardando_pagamento";
  const checkoutUrl = order.checkoutUrl || raw.mp_checkout_url;
  const items = raw.items || [];

  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 1100, background: "var(--bg)", display: "flex", flexDirection: "column" }}>
      <TopBar title={`Pedido #${shortId}`} onBack={onBack} />
      <div style={{ flex: 1, overflow: "auto", padding: "12px 16px 24px" }}>
        {/* partner */}
        <div style={{ display: "flex", alignItems: "center", gap: 12, background: "var(--surface)", borderRadius: 16, padding: "13px 14px", marginBottom: 12 }}>
          <div style={{ width: 42, height: 42, borderRadius: 11, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon name={segIcon(p.seg)} size={22} color="var(--accent)" />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ font: "700 15px var(--ui)", color: "var(--text)" }}>{p.name}</div>
            <div style={{ font: "500 12px var(--ui)", color: "var(--muted)", marginTop: 1 }}>{order.date} · {order.mode}</div>
          </div>
          <StatusChip label={order.status} accent={canReview} warn={awaitingPayment} />
        </div>

        {/* timeline */}
        <div style={{ background: "var(--surface)", borderRadius: 16, padding: "14px 16px", marginBottom: 12 }}>
          <div style={{ font: "700 14px var(--ui)", color: "var(--text)", marginBottom: 4 }}>Acompanhamento</div>
          <StatusTimeline steps={ORDER_STEPS} currentStatus={raw.status || "pendente"} />
        </div>

        {/* items */}
        {items.length > 0 && (
          <div style={{ background: "var(--surface)", borderRadius: 16, padding: "14px 16px", marginBottom: 12 }}>
            <div style={{ font: "700 14px var(--ui)", color: "var(--text)", marginBottom: 10 }}>Itens</div>
            {items.map((it, i) => (
              <div key={it.id || i} style={{ display: "flex", justifyContent: "space-between", padding: "5px 0", borderTop: i ? "1px solid var(--line)" : "none" }}>
                <span style={{ font: "500 13px var(--ui)", color: "var(--text)" }}>{it.quantity}x {it.name}</span>
                <span style={{ font: "700 13px var(--ui)", color: "var(--text)" }}>{money((parseFloat(it.unit_price) || 0) * (it.quantity || 1))}</span>
              </div>
            ))}
          </div>
        )}

        {/* totals */}
        <div style={{ background: "var(--surface)", borderRadius: 16, padding: "14px 16px", marginBottom: 12 }}>
          {raw.subtotal != null && <div style={{ display: "flex", justifyContent: "space-between", padding: "3px 0" }}><span style={{ font: "500 13px var(--ui)", color: "var(--muted)" }}>Subtotal</span><span style={{ font: "700 13px var(--ui)", color: "var(--text)" }}>{money(parseFloat(raw.subtotal) || 0)}</span></div>}
          {raw.taxa_entrega != null && <div style={{ display: "flex", justifyContent: "space-between", padding: "3px 0" }}><span style={{ font: "500 13px var(--ui)", color: "var(--muted)" }}>Entrega</span><span style={{ font: "700 13px var(--ui)", color: "var(--text)" }}>{parseFloat(raw.taxa_entrega) === 0 ? "Grátis" : money(parseFloat(raw.taxa_entrega) || 0)}</span></div>}
          <div style={{ height: 1, background: "var(--line)", margin: "8px 0" }} />
          <div style={{ display: "flex", justifyContent: "space-between", padding: "3px 0" }}><span style={{ font: "700 14px var(--ui)", color: "var(--text)" }}>Total</span><span style={{ font: "800 14px var(--ui)", color: "var(--text)" }}>{money(order.total)}</span></div>
        </div>

        {/* Awaiting payment — banner + action button */}
        {awaitingPayment && (
          <div style={{ background: "#FEF3E2", borderRadius: 16, padding: "16px", marginBottom: 12 }}>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 10, marginBottom: 14 }}>
              <Icon name="coin" size={20} color="#B5751A" style={{ flexShrink: 0, marginTop: 1 }} />
              <div>
                <div style={{ font: "700 14px var(--ui)", color: "#7a4f12", marginBottom: 3 }}>Pagamento pendente</div>
                <div style={{ font: "500 12.5px var(--ui)", color: "#9a6520", lineHeight: 1.45 }}>
                  Seu pedido foi reservado mas ainda não foi pago. Conclua o pagamento para confirmar.
                </div>
              </div>
            </div>
            {checkoutUrl
              ? <Btn full variant="dark" onClick={() => { window.location.href = checkoutUrl; }}>Ir para o Mercado Pago →</Btn>
              : <div style={{ font: "500 12px var(--ui)", color: "#9a6520" }}>Link de pagamento indisponível. Entre em contato com o suporte.</div>
            }
          </div>
        )}

        <div style={{ display: "flex", gap: 10, marginTop: 4 }}>
          <Btn variant="ghost" full onClick={onReorder} style={{ flex: 1 }}>Pedir de novo</Btn>
          {canReview && <Btn onClick={onReview} style={{ flex: 1 }}>Avaliar</Btn>}
        </div>
      </div>
    </div>
  );
}

function ApptDetail({ appt, onBack, onReview }) {
  const raw = appt._raw || {};
  const p = partnerById(appt.partner) || { name: raw.company_name || "Prestador", seg: "saude" };
  const canReview = raw.status === "concluido";

  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 1100, background: "var(--bg)", display: "flex", flexDirection: "column" }}>
      <TopBar title="Detalhes do Agendamento" onBack={onBack} />
      <div style={{ flex: 1, overflow: "auto", padding: "12px 16px 24px" }}>
        {/* partner */}
        <div style={{ display: "flex", alignItems: "center", gap: 12, background: "var(--surface)", borderRadius: 16, padding: "13px 14px", marginBottom: 12 }}>
          <div style={{ width: 42, height: 42, borderRadius: 11, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon name={segIcon(p.seg)} size={22} color="var(--accent)" />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ font: "700 15px var(--ui)", color: "var(--text)" }}>{p.name}</div>
            <div style={{ font: "600 13px var(--ui)", color: "var(--text)", marginTop: 1 }}>{appt.service}</div>
          </div>
          <StatusChip label={appt.status} accent={appt.upcoming || canReview} />
        </div>

        {/* timeline */}
        <div style={{ background: "var(--surface)", borderRadius: 16, padding: "14px 16px", marginBottom: 12 }}>
          <div style={{ font: "700 14px var(--ui)", color: "var(--text)", marginBottom: 4 }}>Acompanhamento</div>
          <StatusTimeline steps={APPT_STEPS} currentStatus={raw.status || "solicitado"} />
        </div>

        {/* details */}
        <div style={{ background: "var(--surface)", borderRadius: 16, padding: "14px 16px", marginBottom: 12 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 0" }}>
            <Icon name="clock" size={16} color="var(--accent)" sw={2} />
            <span style={{ font: "500 13px var(--ui)", color: "var(--text)" }}>{appt.date} · {appt.time}</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 0", borderTop: "1px solid var(--line)" }}>
            <Icon name={appt.local === "loja" ? "store" : "home"} size={16} color="var(--accent)" sw={2} />
            <span style={{ font: "500 13px var(--ui)", color: "var(--text)" }}>{appt.local === "loja" ? "No estabelecimento" : "Na sua casa"}</span>
          </div>
          {raw.service_price != null && (
            <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 0", borderTop: "1px solid var(--line)" }}>
              <Icon name="coin" size={16} color="var(--accent)" sw={2} />
              <span style={{ font: "500 13px var(--ui)", color: "var(--text)" }}>{money(parseFloat(raw.service_price) || 0)}</span>
            </div>
          )}
        </div>

        {canReview && (
          <Btn full onClick={onReview}>Avaliar atendimento</Btn>
        )}
      </div>
    </div>
  );
}

function ComprasScreen({ onReview, onReorder, onAgendaDetail, featureEnabled }) {
  if (!featureEnabled) return (
    <div style={{ position: "absolute", inset: 0, paddingBottom: TAB_H2 }}>
      <EmBreveOverlay icon="bag" title="Suas compras ficam aqui"
        text="Em breve você acompanha pedidos, agendamentos e solicitações de contato com seus parceiros favoritos." />
    </div>
  );
  const [seg, setSeg] = React.useState("pedidos");
  const segs = [["pedidos", "Pedidos"], ["agenda", "Agendamentos"], ["contatos", "Contatos"]];
  const [orderDetail, setOrderDetail] = React.useState(null);
  const [apptDetail, setApptDetail] = React.useState(null);

  // Dados reais da API
  const [apiOrders, setApiOrders] = React.useState(null);
  const [apiAppts, setApiAppts] = React.useState(null);
  const [apiLeads, setApiLeads] = React.useState(null);
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    setLoading(true);
    Promise.all([
      API.orders.list().then(d => setApiOrders((d.orders || []).map(apiOrderToMock))).catch(() => {}),
      API.appointments.list().then(d => setApiAppts((d.appointments || []).map(apiApptToMock))).catch(() => {}),
      API.leads.list().then(d => setApiLeads(d.leads || [])).catch(() => {}),
    ]).finally(() => setLoading(false));
  }, []);

  const orders = apiOrders || ORDERS;
  const appts  = apiAppts  || AGENDAMENTOS;
  const leads  = apiLeads  || LEADS;

  return (
    <div style={{ position: "absolute", inset: 0, overflow: "auto", paddingBottom: TAB_H2 }}>
      <div style={{ padding: "28px 16px 12px" }}>
        <h1 style={{ margin: 0, font: "800 26px var(--ui)", color: "var(--text)" }}>Minhas Compras</h1>
      </div>

      {/* segmented */}
      <div style={{ display: "flex", gap: 4, margin: "0 16px 16px", background: "var(--surface)", borderRadius: 13, padding: 4, boxShadow: "0 2px 8px rgba(16,18,45,.05)" }}>
        {segs.map(([id, lb]) => (
          <button key={id} onClick={() => setSeg(id)} style={{ flex: 1, height: 38, borderRadius: 10, border: "none", cursor: "pointer", background: seg === id ? "var(--brand)" : "transparent", color: seg === id ? "#fff" : "var(--muted)", font: `${seg === id ? 700 : 600} 12.5px var(--ui)` }}>{lb}</button>
        ))}
      </div>

      {loading && <div style={{ textAlign: "center", padding: 40, color: "var(--muted)", font: "500 13px var(--ui)" }}>Carregando…</div>}

      <div style={{ display: "flex", flexDirection: "column", gap: 14, padding: "0 16px" }}>
        {/* PEDIDOS */}
        {seg === "pedidos" && orders.map(o => {
          const p = partnerById(o.partner) || { name: o._raw?.company_name || "Parceiro", seg: "comer" };
          const toRate = !o.rated;
          const isPendingPayment = o.rawStatus === "aguardando_pagamento";
          return (
            <div key={o.id} onClick={() => setOrderDetail(o)} style={{ background: "var(--surface)", borderRadius: 18, overflow: "hidden", boxShadow: "0 3px 12px rgba(16,18,45,.05)", cursor: "pointer" }}>
              {isPendingPayment && (
                <div style={{ background: "#FEF3E2", padding: "8px 15px", display: "flex", alignItems: "center", gap: 8 }}>
                  <Icon name="coin" size={14} color="#B5751A" />
                  <span style={{ font: "600 12px var(--ui)", color: "#7a4f12" }}>Pagamento pendente — toque para continuar</span>
                </div>
              )}
              <div style={{ display: "flex", gap: 12, padding: 15 }}>
                <div style={{ width: 46, height: 46, borderRadius: 12, 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={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
                    <span style={{ font: "700 15px var(--ui)", color: "var(--text)" }}>{p.name}</span>
                    <StatusChip label={o.status} accent={toRate} warn={isPendingPayment} />
                  </div>
                  <div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)", marginTop: 3 }}>{o.items.join(", ")}</div>
                  <div style={{ font: "500 11.5px var(--ui)", color: "var(--muted)", marginTop: 5, display: "flex", alignItems: "center", gap: 8 }}>
                    <span>{o.date}</span><span style={{ opacity: .5 }}>•</span><span>{o.mode}</span><span style={{ opacity: .5 }}>•</span><span style={{ font: "700 12.5px var(--ui)", color: "var(--text)" }}>{money(o.total)}</span>
                  </div>
                  {o.rated && <div style={{ marginTop: 6 }}><Stars value={o.stars} size={13} /></div>}
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 15px", borderTop: "1px solid var(--line)", background: "var(--cb-bg)" }}>
                <Icon name="coin" size={16} color="var(--cb)" sw={1.8} />
                <span style={{ flex: 1, font: "600 12px var(--ui)", color: "var(--cb-ink)" }}>+{money(o.cashback + o.turbo)} de cashback{o.turbo > 0 ? " (com Turbo)" : ""}</span>
              </div>
            </div>
          );
        })}

        {/* AGENDAMENTOS */}
        {seg === "agenda" && appts.map(a => {
          const p = partnerById(a.partner) || { name: a._raw?.company_name || "Prestador", seg: "saude" };
          const toRate = a.status === "Concluído" && !a.rated;
          return (
            <div key={a.id} onClick={() => setApptDetail(a)} style={{ background: "var(--surface)", borderRadius: 18, overflow: "hidden", boxShadow: "0 3px 12px rgba(16,18,45,.05)", cursor: "pointer" }}>
              <div style={{ display: "flex", gap: 12, padding: 15 }}>
                <div style={{ width: 46, height: 46, borderRadius: 12, 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={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
                    <span style={{ font: "700 15px var(--ui)", color: "var(--text)" }}>{p.name}</span>
                    <StatusChip label={a.status} accent={a.upcoming || toRate} />
                  </div>
                  <div style={{ font: "600 12.5px var(--ui)", color: "var(--text)", marginTop: 3 }}>{a.service}</div>
                  <div style={{ font: "500 11.5px var(--ui)", color: "var(--muted)", marginTop: 5, display: "flex", alignItems: "center", gap: 7, flexWrap: "wrap" }}>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 4, whiteSpace: "nowrap" }}><Icon name="clock" size={13} sw={2} />{a.date} · {a.time}</span>
                    <span style={{ opacity: .5 }}>•</span>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 4, whiteSpace: "nowrap" }}><Icon name={a.local === "loja" ? "store" : "home"} size={13} sw={2} />{a.local === "loja" ? "No local" : "Na sua casa"}</span>
                  </div>
                  {a.rated && <div style={{ marginTop: 6 }}><Stars value={a.stars} size={13} /></div>}
                </div>
              </div>
              {a.upcoming && (
                <div style={{ display: "flex", gap: 8, padding: 12, borderTop: "1px solid var(--line)" }}>
                  <Btn variant="ghost" onClick={() => onReorder(a.partner)} style={{ flex: 1, height: 44 }}>Reagendar</Btn>
                  <Btn variant="soft" onClick={() => onAgendaDetail(a)} style={{ flex: 1, height: 44 }}>Ver detalhes</Btn>
                </div>
              )}
            </div>
          );
        })}

        {/* CONTATOS */}
        {seg === "contatos" && leads.map(l => {
          const p = partnerById(l.company_id) || { name: l.company_name || "Parceiro", seg: "morar" };
          return (
            <div key={l.id} style={{ background: "var(--surface)", borderRadius: 18, overflow: "hidden", boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
              <div style={{ display: "flex", gap: 12, padding: 15 }}>
                <div style={{ width: 46, height: 46, borderRadius: 12, 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={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
                    <span style={{ font: "700 15px var(--ui)", color: "var(--text)" }}>{p.name}</span>
                    <StatusChip label={l.status} accent={l.status === "Respondido"} />
                  </div>
                  <div style={{ font: "600 12.5px var(--ui)", color: "var(--text)", marginTop: 3 }}>{l.listing_title || l.title || ""}</div>
                  <div style={{ font: "500 11.5px var(--ui)", color: "var(--muted)", marginTop: 5, display: "flex", alignItems: "center", gap: 5 }}>
                    <Icon name="headset" size={13} sw={2} />{l.channel === "whatsapp" ? "WhatsApp" : "Ligação"} · {l.date || new Date(l.created_at).toLocaleDateString("pt-BR", { day: "2-digit", month: "short" })}
                  </div>
                </div>
              </div>
              <div style={{ display: "flex", gap: 8, padding: 12, borderTop: "1px solid var(--line)" }}>
                <Btn variant="ghost" full onClick={() => onReorder(l.partner)} style={{ height: 44 }}>Ver na vitrine</Btn>
              </div>
            </div>
          );
        })}
      </div>

      {orderDetail && (
        <OrderDetail
          order={orderDetail}
          onBack={() => setOrderDetail(null)}
          onReview={() => { setOrderDetail(null); onReview(orderDetail.partner, orderDetail.mode); }}
          onReorder={() => { setOrderDetail(null); onReorder(orderDetail.partner); }}
        />
      )}
      {apptDetail && (
        <ApptDetail
          appt={apptDetail}
          onBack={() => setApptDetail(null)}
          onReview={() => { setApptDetail(null); onReview(apptDetail.partner, "agenda"); }}
        />
      )}
    </div>
  );
}

// ── Perfil ───────────────────────────────────────────────────
function PerfilEmBreveModal({ icon, title, onClose }) {
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 800, display: "flex", alignItems: "flex-end", justifyContent: "center", background: "rgba(16,18,45,.45)", backdropFilter: "blur(3px)" }}
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{ width: "100%", background: "var(--surface)", borderRadius: "22px 22px 0 0", padding: "24px 24px 40px", boxShadow: "0 -12px 40px rgba(16,18,45,.18)" }}>
        <div style={{ width: 36, height: 4, borderRadius: 99, background: "var(--line)", margin: "0 auto 20px" }} />
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center" }}>
          <div style={{ width: 60, height: 60, borderRadius: 16, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}>
            <Icon name={icon} size={28} color="var(--accent)" />
          </div>
          <div style={{ font: "800 19px var(--ui)", color: "var(--text)", marginBottom: 8 }}>{title}</div>
          <div style={{ font: "500 14px var(--ui)", color: "var(--muted)", lineHeight: 1.6, maxWidth: 290, marginBottom: 24 }}>
            Este recurso estará disponível em breve.<br />
            Enquanto isso, explore os <b style={{ color: "var(--text)" }}>parceiros disponíveis</b> na aba Descobrir e aproveite as melhores opções da sua cidade!
          </div>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "var(--accent)", color: "#fff", borderRadius: 999, padding: "9px 20px", font: "700 13px var(--ui)", marginBottom: 16 }}>
            <Icon name="clock" size={15} color="#fff" />
            Em breve
          </div>
          <button onClick={onClose} style={{ background: "none", border: "none", font: "500 13px var(--ui)", color: "var(--muted)", cursor: "pointer", padding: "6px 0" }}>Fechar</button>
        </div>
      </div>
    </div>
  );
}

function PerfilScreen({ wallet, user, onOpenCarteira, onOpen, onLogout, onOpenClub, clubMember }) {
  const [addrCount, setAddrCount] = React.useState(null);
  const [favCount, setFavCount] = React.useState(null);
  const [canInstall, setCanInstall] = React.useState(false);
  const [showIosHint, setShowIosHint] = React.useState(false);
  const [emBreve, setEmBreve] = React.useState(null); // { icon, title }

  React.useEffect(() => {
    API.me.addresses().then(d => setAddrCount((d.addresses || []).length)).catch(() => {});
    API.me.favorites().then(d => setFavCount((d.favorites || d.companies || []).length)).catch(() => {});

    // PWA: verifica se pode instalar (Android/Chrome)
    if (window.mbCanInstallPWA && window.mbCanInstallPWA()) setCanInstall(true);
    const onInstallable = () => setCanInstall(true);
    const onInstalled  = () => setCanInstall(false);
    window.addEventListener('pwa-installable', onInstallable);
    window.addEventListener('pwa-installed',   onInstalled);

    // iOS: mostra dica se não estiver em modo standalone
    const isIos = /iphone|ipad|ipod/i.test(navigator.userAgent);
    if (isIos && window.mbIsStandalone && !window.mbIsStandalone()) setShowIosHint(true);

    return () => {
      window.removeEventListener('pwa-installable', onInstallable);
      window.removeEventListener('pwa-installed',   onInstalled);
    };
  }, []);

  const rows = [
    ["pin", "Endereços", addrCount != null && addrCount > 0 ? `${addrCount} endereço${addrCount !== 1 ? "s" : ""}` : null, "enderecos"],
    ["card", "Formas de pagamento", "Pix · Cartão MP", "pagamento"],
    ["heart", "Favoritos", favCount != null && favCount > 0 ? `${favCount} favoritado${favCount !== 1 ? "s" : ""}` : null, "favoritos"],
    ["bell", "Notificações", null, "notificacoes"],
    ["ticket", "Cupons", null, "cupons"],
    ["gift", "Indique e ganhe", null, "indique"],
    ["headset", "Ajuda e suporte", null, "ajuda"],
    ["info", "Sobre o Morar Bem", null, "sobre"],
  ];

  const displayName = user?.name || "Usuário";
  const initial = displayName[0].toUpperCase();
  const since = user?.created_at ? new Date(user.created_at).getFullYear() : new Date().getFullYear();

  return (
    <>
    <div style={{ position: "absolute", inset: 0, overflow: "auto", paddingBottom: TAB_H2 }}>
      <div style={{ padding: "58px 16px 18px", display: "flex", alignItems: "center", gap: 14 }}>
        <div style={{ width: 62, height: 62, borderRadius: 999, background: "var(--brand)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", font: "800 24px var(--ui)" }}>{initial}</div>
        <div style={{ flex: 1 }}>
          <h1 style={{ margin: 0, font: "800 21px var(--ui)", color: "var(--text)" }}>{displayName}</h1>
          <div style={{ font: "500 13px var(--ui)", color: "var(--muted)", marginTop: 1 }}>{user?.region_name || "Aracaju"} · Cliente desde {since}</div>
        </div>
        <IconBtn name="edit" size={38} bg="var(--surface)" color="var(--muted)" onClick={() => onOpen("editar")} />
      </div>

      {/* wallet quick */}
      <button onClick={onOpenCarteira} style={{ width: "calc(100% - 32px)", margin: "0 16px", textAlign: "left", cursor: "pointer", border: "none", borderRadius: 18, padding: "15px 16px", background: "var(--brand)", color: "#fff", display: "flex", alignItems: "center", gap: 13 }}>
        <div style={{ width: 42, height: 42, borderRadius: 12, background: "rgba(255,255,255,.16)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="wallet" size={22} color="#fff" /></div>
        <div style={{ flex: 1 }}>
          <div style={{ font: "600 12px var(--ui)", color: "rgba(255,255,255,.72)" }}>Saldo BemCash</div>
          <div style={{ font: "800 19px var(--ui)" }}>{money(wallet.balance)}</div>
        </div>
        <Icon name="chevR" size={18} color="#fff" sw={2.2} />
      </button>

      {/* clube */}
      <button onClick={() => setEmBreve({ icon: "star", title: "Clube Morar Bem" })} style={{ width: "calc(100% - 32px)", margin: "12px 16px 0", textAlign: "left", cursor: "pointer", border: "none", borderRadius: 18, padding: "14px 16px", background: "var(--turbo-grad)", color: "#fff", display: "flex", alignItems: "center", gap: 13, boxShadow: "0 6px 18px var(--turbo-shadow)" }}>
        <div style={{ width: 42, height: 42, borderRadius: 12, background: "rgba(255,255,255,.2)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="star" size={22} color="#fff" fill="#fff" sw={1.5} /></div>
        <div style={{ flex: 1 }}>
          <div style={{ font: "800 15px var(--ui)" }}>Clube Morar Bem</div>
          <div style={{ font: "500 12px var(--ui)", opacity: .92 }}>{clubMember ? "Você é membro · ver benefícios" : "Assine e economize todo mês"}</div>
        </div>
        {clubMember && <span style={{ font: "700 10px var(--ui)", background: "rgba(255,255,255,.25)", padding: "3px 9px", borderRadius: 999 }}>MEMBRO</span>}
        <Icon name="chevR" size={18} color="#fff" sw={2.2} />
      </button>

      <div style={{ margin: "16px 16px 0", background: "var(--surface)", borderRadius: 18, overflow: "hidden", boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
        {rows.map(([ic, lb, val, id], i) => {
          const emBreveIds = { cupons: { icon: "ticket", title: "Cupons" }, indique: { icon: "gift", title: "Indique e Ganhe" } };
          const isEmBreve = !!emBreveIds[id];
          return (
            <button key={lb}
              onClick={() => isEmBreve ? setEmBreve(emBreveIds[id]) : onOpen(id)}
              style={{ width: "100%", display: "flex", alignItems: "center", gap: 13, padding: "14px 16px", background: "none", border: "none", borderTop: i ? "1px solid var(--line)" : "none", cursor: "pointer" }}>
              <Icon name={ic} size={20} color={isEmBreve ? "var(--muted)" : "var(--accent)"} />
              <span style={{ flex: 1, textAlign: "left", font: "600 14.5px var(--ui)", color: "var(--text)" }}>{lb}</span>
              {isEmBreve
                ? <span style={{ font: "600 10.5px var(--ui)", background: "var(--accent-50)", color: "var(--accent)", padding: "3px 9px", borderRadius: 999 }}>Em breve</span>
                : val ? <span style={{ font: "500 12.5px var(--ui)", color: "var(--muted)" }}>{val}</span> : null}
              <Icon name="chevR" size={16} color="var(--line)" sw={2.4} />
            </button>
          );
        })}
      </div>

      {/* Instalar PWA — Android/Chrome */}
      {canInstall && (
        <button onClick={async () => { await window.mbInstallPWA(); setCanInstall(false); }}
          style={{ width: "calc(100% - 32px)", margin: "16px 16px 0", display: "flex", alignItems: "center", gap: 14, padding: "15px 16px", background: "var(--surface)", border: "1.5px solid var(--accent)", borderRadius: 18, cursor: "pointer", boxShadow: "0 4px 14px rgba(63,84,217,.15)" }}>
          <div style={{ width: 42, height: 42, borderRadius: 12, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2v13M8 11l4 4 4-4"/><path d="M3 17v2a2 2 0 002 2h14a2 2 0 002-2v-2"/></svg>
          </div>
          <div style={{ flex: 1, textAlign: "left" }}>
            <div style={{ font: "700 14.5px var(--ui)", color: "var(--accent)" }}>Instalar o app</div>
            <div style={{ font: "500 12px var(--ui)", color: "var(--muted)", marginTop: 2 }}>Adiciona o Morar Bem na sua tela inicial</div>
          </div>
          <Icon name="chevR" size={16} color="var(--accent)" sw={2.4} />
        </button>
      )}

      {/* Instalar PWA — iOS / Safari */}
      {showIosHint && (
        <div style={{ margin: "16px 16px 0", padding: "15px 16px", background: "var(--surface)", border: "1.5px solid var(--line)", borderRadius: 18, boxShadow: "0 4px 14px rgba(16,18,45,.06)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
            <div style={{ width: 38, height: 38, borderRadius: 10, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2v13M8 11l4 4 4-4"/><path d="M3 17v2a2 2 0 002 2h14a2 2 0 002-2v-2"/></svg>
            </div>
            <div style={{ font: "700 14px var(--ui)", color: "var(--text)" }}>Instalar o app no iPhone</div>
          </div>
          <div style={{ font: "500 13px var(--ui)", color: "var(--muted)", lineHeight: 1.55 }}>
            Toque em <b style={{ color: "var(--text)" }}>Compartilhar</b> (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ verticalAlign: "middle" }}><path d="M4 12v8a2 2 0 002 2h12a2 2 0 002-2v-8M16 6l-4-4-4 4M12 2v13"/></svg>) no Safari e depois em <b style={{ color: "var(--text)" }}>"Adicionar à Tela de Início"</b>.
          </div>
        </div>
      )}

      <button onClick={onLogout} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8, margin: "16px auto 0", background: "none", border: "none", cursor: "pointer", font: "700 14px var(--ui)", color: "var(--muted)", padding: 10 }}>
        <Icon name="logout" size={19} color="var(--muted)" />Sair da conta
      </button>
      <div style={{ textAlign: "center", font: "500 11px var(--ui)", color: "var(--muted)", marginTop: 4, opacity: .7 }}>Guia Morar Bem · v1.0</div>
    </div>
    {emBreve && <PerfilEmBreveModal icon={emBreve.icon} title={emBreve.title} onClose={() => setEmBreve(null)} />}
    </>
  );
}

Object.assign(window, { CarteiraScreen, CashbackInfo, ComprasScreen, PerfilScreen, OrderDetail, ApptDetail, StatusTimeline });
