// detail.jsx — vehicle detail page, scheduling modal, contact footer

// ---------- Scheduling calendar modal ----------
const MESES = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
const DIAS_SEM = ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"];

function MiniCalendar({ selected, onSelect }) {
  const today = new Date(); today.setHours(0, 0, 0, 0);
  const [cursor, setCursor] = React.useState(() => new Date(today.getFullYear(), today.getMonth(), 1));
  const maxDate = new Date(today); maxDate.setDate(maxDate.getDate() + 45);

  const year = cursor.getFullYear(), month = cursor.getMonth();
  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < firstDay; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(year, month, d));

  const canPrev = new Date(year, month, 1) > new Date(today.getFullYear(), today.getMonth(), 1);
  const canNext = new Date(year, month + 1, 1) <= maxDate;
  const sameDay = (a, b) => a && b && a.toDateString() === b.toDateString();

  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <button disabled={!canPrev} onClick={() => setCursor(new Date(year, month - 1, 1))} className="btn btn-ghost btn-sm" style={{ padding: 8, borderRadius: 9 }}><IconArrowLeft size={16} /></button>
        <strong style={{ fontFamily: "var(--font-display)", fontSize: 16 }}>{MESES[month]} {year}</strong>
        <button disabled={!canNext} onClick={() => setCursor(new Date(year, month + 1, 1))} className="btn btn-ghost btn-sm" style={{ padding: 8, borderRadius: 9 }}><IconArrowRight size={16} /></button>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 4, textAlign: "center" }}>
        {DIAS_SEM.map((d) => <div key={d} style={{ fontSize: 11, fontWeight: 700, color: "var(--faint)", padding: "4px 0" }}>{d}</div>)}
        {cells.map((date, i) => {
          if (!date) return <div key={i} />;
          const past = date < today;
          const tooFar = date > maxDate;
          const closed = !STORE.diasAtendimento.includes(date.getDay());
          const disabled = past || tooFar || closed;
          const sel = sameDay(date, selected);
          return (
            <button key={i} disabled={disabled} onClick={() => onSelect(date)} style={{
              aspectRatio: "1", borderRadius: 9, border: "1px solid " + (sel ? "var(--accent)" : "transparent"),
              background: sel ? "var(--accent)" : disabled ? "transparent" : "var(--surface-2)",
              color: sel ? "var(--accent-ink)" : disabled ? "var(--faint)" : "var(--text)",
              fontWeight: sel ? 800 : 600, fontSize: 14, cursor: disabled ? "not-allowed" : "pointer",
              opacity: disabled ? .4 : 1, transition: "all .12s",
            }}>{date.getDate()}</button>
          );
        })}
      </div>
    </div>
  );
}

function SchedulingModal({ open, onClose, vehicle }) {
  const [date, setDate] = React.useState(null);
  const [time, setTime] = React.useState(null);
  const [nome, setNome] = React.useState("");
  const [tel, setTel] = React.useState("");
  const [done, setDone] = React.useState(false);

  React.useEffect(() => { if (open) { setDate(null); setTime(null); setNome(""); setTel(""); setDone(false); } }, [open, vehicle]);
  if (!vehicle) return null;

  const fmtDate = (d) => d ? `${d.getDate()} de ${MESES[d.getMonth()].toLowerCase()}` : "";
  const ready = date && time && nome.trim() && tel.trim();

  const confirm = () => setDone(true);
  const waText = `Olá! Quero agendar uma visita para ver o *${vehicle.marca} ${vehicle.modelo} ${vehicle.ano}*.\n\n📅 Dia: ${fmtDate(date)}\n🕐 Horário: ${time}\n👤 Nome: ${nome}\n📞 Telefone: ${tel}`;

  return (
    <Modal open={open} onClose={onClose} maxWidth={520} label="Agendar visita">
      {done ? (
        <div style={{ padding: "40px 28px", textAlign: "center" }}>
          <div style={{ width: 64, height: 64, borderRadius: "50%", background: "color-mix(in oklch, var(--ok) 18%, transparent)", color: "var(--ok)", display: "grid", placeItems: "center", margin: "0 auto 18px" }}>
            <IconCheckCircle size={36} />
          </div>
          <h3 style={{ fontSize: 22 }}>Visita agendada!</h3>
          <p style={{ color: "var(--muted)", marginTop: 8, lineHeight: 1.55 }}>
            {nome.split(" ")[0]}, sua visita para ver o <strong style={{ color: "var(--text)" }}>{vehicle.modelo}</strong> está marcada para<br />
            <strong style={{ color: "var(--accent)" }}>{fmtDate(date)} às {time}</strong>.
          </p>
          <p style={{ color: "var(--faint)", fontSize: 13.5, marginTop: 10 }}>Confirme pelo WhatsApp para garantir seu horário — o vendedor responde rapidinho.</p>
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 22 }}>
            <a href={waLink(waText)} target="_blank" rel="noopener" className="btn btn-wa btn-lg btn-block"><IconWhats size={18} /> Confirmar pelo WhatsApp</a>
            <button onClick={onClose} className="btn btn-ghost btn-block">Fechar</button>
          </div>
        </div>
      ) : (
        <>
          <ModalHeader title="Agendar visita" subtitle={`${vehicle.marca} ${vehicle.modelo} · ${vehicle.ano}`} onClose={onClose} />
          <div style={{ padding: 22, display: "flex", flexDirection: "column", gap: 22 }}>
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, fontWeight: 700, color: "var(--muted)", marginBottom: 12 }}><IconCalDay size={16} /> 1. Escolha o dia</div>
              <MiniCalendar selected={date} onSelect={(d) => { setDate(d); setTime(null); }} />
            </div>
            {date && (
              <div className="fade-in">
                <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, fontWeight: 700, color: "var(--muted)", marginBottom: 12 }}><IconClock size={16} /> 2. Escolha o horário</div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
                  {STORE.horarios.map((h) => (
                    <button key={h} onClick={() => setTime(h)} className="chip" data-active={time === h} style={{ justifyContent: "center", padding: "10px 0" }}>{h}</button>
                  ))}
                </div>
              </div>
            )}
            {time && (
              <div className="fade-in" style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, fontWeight: 700, color: "var(--muted)" }}><IconUser size={16} /> 3. Seus dados</div>
                <div className="field"><label>Nome</label><input className="input" value={nome} onChange={(e) => setNome(e.target.value)} placeholder="Seu nome" /></div>
                <div className="field"><label>Telefone / WhatsApp</label><input className="input" value={tel} onChange={(e) => setTel(e.target.value)} placeholder="(11) 99999-9999" /></div>
              </div>
            )}
            <button disabled={!ready} onClick={confirm} className="btn btn-primary btn-lg btn-block">
              {ready ? <>Confirmar agendamento <IconCheck size={18} /></> : "Preencha dia, horário e dados"}
            </button>
          </div>
        </>
      )}
    </Modal>
  );
}

// ---------- Vehicle detail page ----------
function VehicleDetail({ vehicle, onBack, onSchedule }) {
  const [activeFoto, setActiveFoto] = React.useState(0);
  React.useEffect(() => { setActiveFoto(0); window.scrollTo(0, 0); }, [vehicle && vehicle.id]);
  if (!vehicle) return null;
  const fotos = vehicle.fotos && vehicle.fotos.length ? vehicle.fotos : [null];
  const sold = vehicle.status === "vendido";
  const isOferta = vehicle.status === "oferta" && vehicle.precoAntigo > vehicle.preco;
  const desconto = isOferta ? Math.round((1 - vehicle.preco / vehicle.precoAntigo) * 100) : 0;
  const galVehicle = { ...vehicle, fotos: fotos[activeFoto] ? [fotos[activeFoto]] : [] };

  const waText = `Olá! Tenho interesse no *${vehicle.marca} ${vehicle.modelo} ${vehicle.ano}* (${formatBRL(vehicle.preco)}). Ainda está disponível?`;

  return (
    <div className="wrap fade-in" style={{ paddingTop: 24, paddingBottom: 60 }}>
      <button onClick={onBack} className="btn btn-ghost btn-sm" style={{ marginBottom: 20 }}><IconArrowLeft size={16} /> Voltar ao estoque</button>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.5fr) minmax(0, 1fr)", gap: 32, alignItems: "start" }} className="detail-grid">
        {/* gallery + info */}
        <div>
          <div className="card" style={{ overflow: "hidden", position: "relative" }}>
            <div style={{ position: "relative", aspectRatio: "16 / 11" }}>
              <VehiclePhoto vehicle={galVehicle} style={{ width: "100%", height: "100%" }} rounded={false} />
              <div style={{ position: "absolute", top: 16, left: 16, display: "flex", gap: 8 }}>
                <StatusBadge status={vehicle.status} />
                {isOferta && <span className="badge" style={{ background: "var(--danger)", color: "#fff" }}>-{desconto}%</span>}
              </div>
            </div>
          </div>
          {fotos.length > 1 && (
            <div style={{ display: "flex", gap: 10, marginTop: 12, overflowX: "auto", paddingBottom: 4 }}>
              {fotos.map((f, i) => (
                <button key={i} onClick={() => setActiveFoto(i)} style={{ flexShrink: 0, width: 92, aspectRatio: "4/3", borderRadius: 10, overflow: "hidden", border: "2px solid " + (i === activeFoto ? "var(--accent)" : "transparent"), padding: 0, cursor: "pointer", background: "none" }}>
                  <VehiclePhoto vehicle={{ ...vehicle, fotos: f ? [f] : [] }} style={{ width: "100%", height: "100%" }} rounded={false} label={false} />
                </button>
              ))}
            </div>
          )}

          {/* specs */}
          <div className="card" style={{ padding: 22, marginTop: 22 }}>
            <h3 style={{ fontSize: 17, marginBottom: 18 }}>Ficha técnica</h3>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 18 }}>
              <SpecPill icon={IconCalendar} label="Ano" value={vehicle.ano} />
              <SpecPill icon={IconGauge} label="Quilometragem" value={formatKM(vehicle.km)} />
              <SpecPill icon={IconGear} label="Câmbio" value={vehicle.cambio} />
              <SpecPill icon={IconFuel} label="Combustível" value={vehicle.combustivel} />
              <SpecPill icon={IconPalette} label="Cor" value={vehicle.cor} />
              <SpecPill icon={IconBike} label="Segmento" value={segLabel(vehicle.categoria)} />
            </div>
          </div>

          {/* description */}
          {vehicle.descricao && (
            <div className="card" style={{ padding: 22, marginTop: 22 }}>
              <h3 style={{ fontSize: 17, marginBottom: 12 }}>Descrição</h3>
              <p style={{ color: "var(--muted)", lineHeight: 1.65, whiteSpace: "pre-wrap" }}>{vehicle.descricao}</p>
            </div>
          )}

          {/* opcionais */}
          {vehicle.opcionais && vehicle.opcionais.length > 0 && (
            <div className="card" style={{ padding: 22, marginTop: 22 }}>
              <h3 style={{ fontSize: 17, marginBottom: 14 }}>Opcionais e itens</h3>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 9 }}>
                {vehicle.opcionais.map((o) => (
                  <span key={o} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "8px 13px", borderRadius: 999, background: "var(--surface-2)", border: "1px solid var(--border-soft)", fontSize: 13.5, fontWeight: 600 }}>
                    <IconCheck size={14} style={{ color: "var(--accent)" }} />{o}
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* sticky sidebar */}
        <div style={{ position: "sticky", top: 88, display: "flex", flexDirection: "column", gap: 16 }} className="detail-side">
          <div className="card" style={{ padding: 24 }}>
            <div style={{ fontSize: 13, color: "var(--faint)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em" }}>{vehicle.marca} · {vehicle.ano}</div>
            <h1 style={{ fontSize: 30, marginTop: 4 }}>{vehicle.modelo}</h1>
            <div style={{ marginTop: 16 }}>
              {isOferta && <div style={{ fontSize: 15, color: "var(--faint)", textDecoration: "line-through" }}>{formatBRL(vehicle.precoAntigo)}</div>}
              <div style={{ fontFamily: "var(--font-display)", fontSize: 38, fontWeight: 700, color: isOferta ? "var(--warn)" : "var(--text)", lineHeight: 1 }}>{formatBRL(vehicle.preco)}</div>
              {isOferta && <div style={{ fontSize: 13.5, color: "var(--ok)", fontWeight: 700, marginTop: 6 }}>Economize {formatBRL(vehicle.precoAntigo - vehicle.preco)}</div>}
            </div>

            {sold ? (
              <div style={{ marginTop: 22, padding: "14px 16px", borderRadius: 12, background: "color-mix(in oklch, var(--danger) 14%, transparent)", color: "oklch(0.8 0.12 25)", fontWeight: 700, textAlign: "center" }}>
                Este veículo já foi vendido
              </div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 22 }}>
                <button onClick={() => onSchedule(vehicle)} className="btn btn-primary btn-lg btn-block"><IconCalendar size={18} /> Agendar visita</button>
                <a href={waLink(waText)} target="_blank" rel="noopener" className="btn btn-wa btn-lg btn-block"><IconWhats size={18} /> Falar no WhatsApp</a>
              </div>
            )}
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 16, fontSize: 12.5, color: "var(--faint)", justifyContent: "center" }}>
              <IconShield size={15} /> Atendimento direto com o vendedor
            </div>
          </div>

          <div className="card" style={{ padding: 18 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, fontWeight: 700, fontSize: 14, marginBottom: 12 }}><IconPin size={17} style={{ color: "var(--accent)" }} /> Onde estamos</div>
            <StoreMap height={130} />
            <p style={{ fontSize: 13, color: "var(--muted)", marginTop: 12, lineHeight: 1.5 }}>{STORE.endereco}</p>
            <p style={{ fontSize: 12.5, color: "var(--faint)", marginTop: 6, display: "flex", alignItems: "center", gap: 6 }}><IconClock size={14} /> {STORE.horario}</p>
          </div>
        </div>
      </div>
      <style>{`@media (max-width: 880px){ .detail-grid{ grid-template-columns: 1fr !important; } .detail-side{ position: static !important; } }`}</style>
    </div>
  );
}

// ---------- Contact footer ----------
function Footer() {
  return (
    <footer id="contato" style={{ borderTop: "1px solid var(--border-soft)", background: "var(--surface)", scrollMarginTop: 80 }}>
      <div className="wrap" style={{ padding: "48px 24px 36px", display: "grid", gridTemplateColumns: "1.3fr 1fr 1.2fr", gap: 36 }}>
        <div className="foot-grid-item">
          <div style={{ marginBottom: 14 }}><Brand size={46} /></div>
          <p style={{ color: "var(--muted)", lineHeight: 1.6, maxWidth: 300, fontSize: 14.5 }}>Concessionária de motos em Porto Alegre, há mais de 10 anos realizando sonhos. O maior estoque de usadas da cidade — agende sua visita ou fale com a gente pelo WhatsApp e Instagram.</p>
          <div style={{ display: "flex", gap: 10, marginTop: 18, flexWrap: "wrap" }}>
            <a href={waLink("Olá! Vim pelo site da Moliterni Motos.")} target="_blank" rel="noopener" className="btn btn-wa btn-sm"><IconWhats size={16} /> {STORE.whatsappDisplay}</a>
            <a href={STORE.instagramUrl} target="_blank" rel="noopener" className="btn btn-ig btn-sm"><IconInsta size={16} /> @{STORE.instagram}</a>
          </div>
        </div>
        <div className="foot-grid-item">
          <h4 style={{ fontSize: 14, marginBottom: 14, color: "var(--faint)", textTransform: "uppercase", letterSpacing: ".05em" }}>Contato</h4>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 11, color: "var(--muted)", fontSize: 14.5 }}>
            <li style={{ display: "flex", gap: 9 }}><IconPin size={17} style={{ flexShrink: 0, color: "var(--accent)" }} />{STORE.endereco}</li>
            <li style={{ display: "flex", gap: 9 }}><IconClock size={17} style={{ flexShrink: 0, color: "var(--accent)" }} />{STORE.horario}</li>
            <li style={{ display: "flex", gap: 9 }}><IconPhone size={17} style={{ flexShrink: 0, color: "var(--accent)" }} />{STORE.whatsappDisplay}</li>
            <li style={{ display: "flex", gap: 9 }}><IconInsta size={17} style={{ flexShrink: 0, color: "var(--accent)" }} />@{STORE.instagram}</li>
          </ul>
        </div>
        <div className="foot-grid-item">
          <h4 style={{ fontSize: 14, marginBottom: 14, color: "var(--faint)", textTransform: "uppercase", letterSpacing: ".05em" }}>Localização</h4>
          <StoreMap height={140} />
        </div>
      </div>
      <div style={{ borderTop: "1px solid var(--border-soft)" }}>
        <div className="wrap" style={{ padding: "18px 24px", display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 10, fontSize: 13, color: "var(--faint)" }}>
          <span>© {new Date().getFullYear()} Moliterni Motos · Protótipo de demonstração</span>
          <span>Atendimento direto com o vendedor</span>
        </div>
      </div>
      <style>{`@media (max-width: 760px){ #contato .wrap[style*="grid-template-columns"]{ grid-template-columns: 1fr !important; } }`}</style>
    </footer>
  );
}

Object.assign(window, { SchedulingModal, VehicleDetail, Footer, MiniCalendar });
