/* app.jsx — root, header, footer, router */
const { useState: useSt, useEffect: useEf, useRef: useRf } = React;

const NAV = [
{ id: "home", label: "Home" },
{ id: "morar", label: "Morar" },
{ id: "investir", label: "Investir" },
{ id: "litoral", label: "Litoral" },
{ id: "curadoria", label: "Curadoria" },
{ id: "sobre", label: "Sobre" },
{ id: "contato", label: "Contato" }];


/* The pages that show dark hero immediately — used to flip header style */
const DARK_HERO_PAGES = new Set(["home", "morar", "investir", "litoral", "curadoria", "sobre"]);

function Header({ page, go, openContact }) {
  const [scrolled, setScrolled] = useSt(false);
  useEf(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const onDark = DARK_HERO_PAGES.has(page) && !scrolled;
  const headerClass = `hd ${onDark ? "on-dark" : "on-light"} ${scrolled ? "compact" : ""}`;

  return (
    <header className={headerClass}>
      <div className="brand" onClick={() => go("home")}>
        <img src="assets/logo-10house.svg" alt="10HOUSE" className="brand-logo" />
      </div>
      <nav>
        {NAV.filter((n) => !["home", "contato"].includes(n.id)).map((n) =>
        <a key={n.id} className={page === n.id ? "active" : ""} onClick={() => go(n.id)}>{n.label}</a>
        )}
      </nav>
      <div className="right">
        <button className="priv" onClick={openContact}>
          <span className="pulse"></span>
          <span><span className="long">Atendimento </span>privado</span>
        </button>
      </div>
    </header>);

}

function Footer({ go, openContact }) {
  const edition = window.S.currentEdition();
  const wa = (msg) => `https://wa.me/5541997111147?text=${encodeURIComponent(msg)}`;
  const TERRITORIOS = [
  { label: "Imobiliário", msg: "Olá, 10HOUSE. Tenho interesse no território Imobiliário — gostaria de conhecer imóveis de alto padrão selecionados." },
  { label: "Arquitetura", msg: "Olá, 10HOUSE. Tenho interesse no território Arquitetura — gostaria de indicações de arquitetos, interiores e fornecedores premium." },
  { label: "Lifestyle", msg: "Olá, 10HOUSE. Tenho interesse no território Lifestyle — gostaria de conhecer experiências, marcas e parceiros." },
  { label: "Mobilidade", msg: "Olá, 10HOUSE. Tenho interesse no território Mobilidade — automotivo, náutico (barcos e lanchas) ou aviação executiva (aviões e jatos)." },
  { label: "Crédito", msg: "Olá, 10HOUSE. Tenho interesse no território Crédito — gostaria de falar sobre financiamento, consórcio ou consórcio contemplado." }];

  return (
    <footer className="ft" style={{ position: "relative", overflow: "hidden" }}>
      <div className="watermark" style={{ color: "var(--paper)", opacity: 0.045 }}>10<i>HOUSE</i></div>
      <div className="ft-grid" style={{ position: "relative" }}>
        <div>
          <img src="assets/logo-10house.svg" alt="10HOUSE" style={{ height: 28, width: "auto", display: "block", marginBottom: 18, filter: "brightness(1.05)" }} />
          <p style={{ color: "rgba(250,247,240,0.65)", fontSize: 13.5, lineHeight: 1.65, maxWidth: 360, margin: 0 }}>
            Curadoria privada de imóveis e crédito — financiamento e consórcio contemplado junto ao imóvel —, arquitetura e parceiros premium. Em Curitiba e no litoral catarinense, sob agendamento.
          </p>
          <div style={{ marginTop: 32 }}>
            <button className="btn on-dark" onClick={openContact}>Solicite atendimento<span className="arr"></span></button>
          </div>
        </div>

        <div>
          <h4>Curadoria</h4>
          <ul>
            {TERRITORIOS.map((t) =>
            <li key={t.label}><a href={wa(t.msg)} target="_blank" rel="noopener noreferrer">{t.label}</a></li>
            )}
          </ul>
        </div>

        <div>
          <h4>A 10HOUSE</h4>
          <ul>
            <li><a onClick={() => go("sobre")}>Sobre</a></li>
            <li><a onClick={() => go("curadoria")}>Filosofia</a></li>
            <li><a href={wa("Olá, 10HOUSE. Tenho interesse em parcerias — gostaria de conversar sobre uma parceria com a 10HOUSE.")} target="_blank" rel="noopener noreferrer">Parcerias</a></li>
          </ul>
        </div>

        <div>
          <h4>Contato</h4>
          <ul>
            <li><a href={wa("Olá, 10HOUSE. Gostaria de falar com a curadoria.")} target="_blank" rel="noopener noreferrer">WhatsApp · (41) 99711-1147</a></li>
            <li><a href="mailto:contato@10house.com.br">contato@10house.com.br</a></li>
            <li><a>Av. República Argentina, 1228 · Sala 1701</a></li>
            <li><a href="https://instagram.com/10house" target="_blank" rel="noopener noreferrer">@10housebr</a></li>
          </ul>
        </div>
      </div>

      <div className="ft-bottom" style={{ position: "relative" }}>
        <span>© {edition.yearRoman} · 10HOUSE Curadoria Imobiliária</span>
        <span style={{ fontFamily: "var(--serif)", fontStyle: "italic", color: "rgba(232,217,179,0.6)", letterSpacing: 0, textTransform: "none", fontSize: 14 }}>
          edição {edition.season.toLowerCase()}
        </span>
        <span className="creci">CRECI 9088-J</span>
      </div>
    </footer>);

}

/* Contact sheet */
function ContactSheet({ open, onClose }) {
  const { Sheet, NumLabel, Eyebrow } = window.S;
  const [form, setForm] = useSt({ name: "", phone: "", email: "", interest: "Morar em Curitiba", note: "" });
  const [sent, setSent] = useSt(false);
  useEf(() => {if (open) setSent(false);}, [open]);

  return (
    <Sheet open={open} onClose={onClose}>
      <div className="eyebrow"><span className="dot"></span>Atendimento privado</div>
      <h2 className="h2" style={{ margin: "20px 0 8px", fontSize: "clamp(28px, 4vw, 44px)" }}>
        Solicite uma <em style={{ fontStyle: "italic" }}>conversa.</em>
      </h2>
      <p className="body" style={{ marginBottom: 32 }}>
        Sob agendamento — um membro da curadoria entrará em contato em até 24h.
      </p>

      {sent ?
      <div style={{ borderTop: "1px solid var(--rule)", paddingTop: 32 }}>
          <div style={{ fontFamily: "var(--serif)", fontStyle: "italic", color: "var(--gold)", fontSize: 28 }}>obrigado.</div>
          <p className="body" style={{ marginTop: 14 }}>
            Sua solicitação foi recebida. Você receberá em breve uma confirmação no email indicado.
          </p>
          <div style={{ marginTop: 28 }}>
            <button className="btn" onClick={onClose}>Fechar<span className="arr"></span></button>
          </div>
        </div> :

      <form onSubmit={(e) => {e.preventDefault();setSent(true);}}>
          <div className="field">
            <label>Nome</label>
            <input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
          </div>
          <div className="field">
            <label>Telefone</label>
            <input required value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="(__) _____-____" />
          </div>
          <div className="field">
            <label>Email</label>
            <input required type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
          </div>
          <div className="field">
            <label>Interesse</label>
            <select value={form.interest} onChange={(e) => setForm({ ...form, interest: e.target.value })}>
              <option>Morar em Curitiba</option>
              <option>Investir</option>
              <option>Litoral catarinense</option>
              <option>Curadoria privada</option>
            </select>
          </div>
          <div className="field">
            <label>Observação</label>
            <textarea value={form.note} onChange={(e) => setForm({ ...form, note: e.target.value })} placeholder="Opcional" />
          </div>
          <div style={{ marginTop: 16 }}>
            <button type="submit" className="btn">Enviar<span className="arr"></span></button>
          </div>
        </form>
      }
    </Sheet>);

}

/* Property detail sheet */
function PropertySheet({ property, onClose, openContact }) {
  const { Sheet, Ph } = window.S;
  if (!property) return null;
  const p = property;

  return (
    <Sheet open={!!property} onClose={onClose}>
      <div className="eyebrow"><span className="dot"></span>{p.ref}</div>
      <div style={{ position: "relative", marginTop: 20, marginBottom: 28, aspectRatio: "5/4" }}>
        <Ph tag={p.tag || "atmosfera"} tone={p.tone} src={p.src} pos={p.pos} num={p.ref} style={{ position: "absolute", inset: 0 }} />
      </div>

      <h2 className="h2" style={{ margin: 0, fontSize: "clamp(28px, 4vw, 40px)" }}>{p.title}</h2>
      {p.subtitle && <div style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 20, color: "var(--gold)", marginTop: 6 }}>{p.subtitle}</div>}
      <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--ink-3)", marginTop: 12 }}>
        {p.neighborhood} · {p.city}
      </div>

      <p className="lede" style={{ marginTop: 24 }}>{p.blurb}</p>

      {p.pitch &&
      <div style={{ marginTop: 40, padding: "36px 0 8px", borderTop: "1px solid var(--rule)", borderBottom: "1px solid var(--rule-soft)" }}>
          <div className="eyebrow" style={{ marginBottom: 18 }}>{p.pitch.kicker}</div>
          <h3 style={{ margin: 0, fontFamily: "var(--serif)", fontSize: "clamp(28px, 3.4vw, 44px)", fontWeight: 300, lineHeight: 1.05, letterSpacing: "-0.005em" }}>
            {p.pitch.headline.split(".").filter(Boolean).map((s, i, a) =>
          <span key={i}>
                {s.trim()}
                {i < a.length - 1 || p.pitch.headline.endsWith(".") ? <em style={{ fontStyle: "italic", color: "var(--gold)" }}>.</em> : null}
                {i < a.length - 1 ? <br /> : null}
              </span>
          )}
          </h3>
          {p.pitch.lede && <p className="body" style={{ marginTop: 22, fontSize: 15, lineHeight: 1.75 }}>{p.pitch.lede}</p>}
        </div>
      }

      {p.gallery && p.gallery.length > 0 &&
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginTop: 32 }}>
          {p.gallery.map((g, i) =>
        <div key={i} style={{ position: "relative", aspectRatio: "4/3", overflow: "hidden" }}>
              <div style={{ position: "absolute", inset: 0, backgroundImage: `url(${g.src})`, backgroundSize: 'cover', backgroundPosition: 'center', transition: 'transform 1200ms cubic-bezier(.22,.61,.36,1)' }}
          onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.04)'}
          onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}></div>
              <div style={{
            position: "absolute", bottom: 0, left: 0, right: 0, padding: "20px 12px 8px",
            background: "linear-gradient(180deg, transparent, rgba(14,32,24,0.85))",
            color: "var(--paper)", fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: "0.2em", textTransform: "uppercase"
          }}>{g.caption}</div>
            </div>
        )}
        </div>
      }

      {p.metrics &&
      <div style={{ marginTop: 36 }}>
          <div className="eyebrow" style={{ marginBottom: 16 }}>Dossiê · investimento</div>
          <div style={{ borderTop: "1px solid var(--rule)" }}>
            {p.metrics.map((m, i) =>
          <div key={i} style={{
            display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 16,
            padding: "14px 0", borderBottom: "1px solid var(--rule-soft)",
            alignItems: "baseline"
          }}>
                <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--ink-3)" }}>{m.k}</div>
                <div style={{ fontFamily: "var(--serif)", fontSize: 17, color: "var(--ink)" }}>{m.v}</div>
              </div>
          )}
          </div>
        </div>
      }

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 0, marginTop: 32 }}>
        {[
        ["Área", p.area],
        ["Suítes", p.suites],
        p.parking ? ["Vagas", p.parking] : null,
        ["Status", p.status],
        ["Valor", p.price]].
        filter(Boolean).map(([k, v], i) =>
        <div key={k} style={{ padding: "16px 0", borderTop: "1px solid var(--rule)" }}>
            <div className="eyebrow">{k}</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 18, marginTop: 6 }}>{v}</div>
          </div>
        )}
      </div>

      <div style={{ marginTop: 32, display: "flex", gap: 12, flexWrap: "wrap" }}>
        <button className="btn" onClick={() => window.S.openWa(`Olá, 10HOUSE. Tenho interesse no imóvel ${p.ref} — ${p.title} (${p.neighborhood} · ${p.city}). Gostaria de agendar uma visita.`)}>Solicitar visita<span className="arr"></span></button>
        <button className="btn" style={{ background: "var(--forest)", borderColor: "var(--forest)", color: "var(--paper)" }} onClick={() => window.S.openWa(`Olá, 10HOUSE. Gostaria de falar com a curadoria sobre o imóvel ${p.ref} — ${p.title} (${p.neighborhood} · ${p.city}).`)}>WhatsApp curadoria<span className="arr"></span></button>
      </div>

      <p style={{ marginTop: 24, fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--ink-3)", lineHeight: 1.7 }}>
        Imagens com sugestão de decoração. Mobiliário e equipamentos apresentados não fazem parte do contrato de aquisição. Consulte memorial descritivo.<br />
        Atendimento reservado · mediante agendamento
      </p>
    </Sheet>);

}

/* Scroll progress bar */
function ScrollProgress() {
  const ref = useRf(null);
  useEf(() => {
    const onScroll = () => {
      const el = ref.current;
      if (!el) return;
      const h = document.documentElement.scrollHeight - window.innerHeight;
      const p = h > 0 ? window.scrollY / h * 100 : 0;
      el.style.width = p + "%";
      el.style.opacity = p > 1 ? "0.85" : "0";
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return <div id="scroll-progress" ref={ref}></div>;
}

/* Root app */
function App() {
  const [page, setPage] = useSt("home");
  const [leaving, setLeaving] = useSt(false);
  const [contactOpen, setContactOpen] = useSt(false);
  const [property, setProperty] = useSt(null);

  /* Tweaks */
  const [t, setTweak] = window.useTweaks(/*EDITMODE-BEGIN*/{
    "palette": "cream",
    "displayFont": "Cormorant Garamond",
    "accent": "gold"
  } /*EDITMODE-END*/);

  useEf(() => {
    const palettes = {
      cream: { "--bg": "#eee7d6", "--bg-warm": "#e4dcc7", "--paper": "#f7f1e2", "--ink": "#0e2018", "--ink-2": "#2b4338", "--ink-3": "#5c7165", "--rule": "rgba(28, 61, 46, 0.18)", "--rule-soft": "rgba(28, 61, 46, 0.09)" },
      stone: { "--bg": "#e3ddcc", "--bg-warm": "#d8d1bd", "--paper": "#f0eada", "--ink": "#0d1f17", "--ink-2": "#2f4438", "--ink-3": "#5f7166", "--rule": "rgba(28, 61, 46, 0.22)", "--rule-soft": "rgba(28, 61, 46, 0.1)" },
      ivory: { "--bg": "#f3ecdc", "--bg-warm": "#ebe2d0", "--paper": "#faf4e6", "--ink": "#0e2018", "--ink-2": "#2b4338", "--ink-3": "#5d7166", "--rule": "rgba(28, 61, 46, 0.16)", "--rule-soft": "rgba(28, 61, 46, 0.08)" },
      forest: { "--bg": "#dbe2d8", "--bg-warm": "#cdd6c8", "--paper": "#e6ebe2", "--ink": "#0a1c14", "--ink-2": "#1f3a2d", "--ink-3": "#4f6859", "--rule": "rgba(28, 61, 46, 0.26)", "--rule-soft": "rgba(28, 61, 46, 0.12)" },
      onyx: { "--bg": "#0e1d15", "--bg-warm": "#142519", "--paper": "#f7f1e2", "--ink": "#e8e0c8", "--ink-2": "#cfc7af", "--ink-3": "#8a8772", "--rule": "rgba(217, 189, 134, 0.2)", "--rule-soft": "rgba(217, 189, 134, 0.1)" }
    };
    const accents = {
      gold: { "--gold": "#b89556", "--gold-soft": "#d9bd86", "--champagne": "#e8d9b3" },
      bronze: { "--gold": "#a87340", "--gold-soft": "#cf9d6b", "--champagne": "#e3c9a8" },
      sage: { "--gold": "#7a8a6b", "--gold-soft": "#a4b395", "--champagne": "#c8d3bb" }
    };
    const fonts = {
      "Cormorant Garamond": { "--serif": "\"Cormorant Garamond\", Georgia, serif" },
      "Cardo": { "--serif": "\"Cardo\", Georgia, serif" },
      "Tenor Sans": { "--serif": "\"Tenor Sans\", Georgia, serif" }
    };
    const tokens = { ...palettes[t.palette], ...accents[t.accent], ...fonts[t.displayFont] };
    Object.entries(tokens).forEach(([k, v]) => document.documentElement.style.setProperty(k, v));
  }, [t.palette, t.accent, t.displayFont]);

  const go = (id) => {
    if (id === page) return;
    setLeaving(true);
    setTimeout(() => {
      setPage(id);
      window.scrollTo({ top: 0, behavior: "instant" });
      setLeaving(false);
    }, 240);
  };

  // Every contact CTA opens WhatsApp directly. Accepts an optional message
  // string; guards against being passed a click event by onClick={openContact}.
  const openContact = (msg) => window.S.openWa(typeof msg === "string" && msg ? msg : undefined);
  const openProperty = (p) => setProperty(p);

  const P = window.Pages;
  let PageEl = null;
  if (page === "home") PageEl = <P.HomePage go={go} openContact={openContact} openProperty={openProperty} />;
  if (page === "morar") PageEl = <P.MorarPage openContact={openContact} openProperty={openProperty} />;
  if (page === "investir") PageEl = <P.InvestirPage openContact={openContact} openProperty={openProperty} />;
  if (page === "litoral") PageEl = <P.LitoralPage openContact={openContact} openProperty={openProperty} />;
  if (page === "curadoria") PageEl = <P.CuradoriaPage openContact={openContact} />;
  if (page === "sobre") PageEl = <P.SobrePage openContact={openContact} />;
  if (page === "contato") PageEl = <P.ContatoPage openContact={openContact} />;

  return (
    <>
      <ScrollProgress />
      <Header page={page} go={go} openContact={openContact} />
      <main key={page} className={leaving ? "leaving-wrap" : ""}>{PageEl}</main>
      <Footer go={go} openContact={openContact} />
      <ContactSheet open={contactOpen} onClose={() => setContactOpen(false)} />
      <PropertySheet property={property} onClose={() => setProperty(null)} openContact={() => {setProperty(null);setContactOpen(true);}} />

      {/* Tweaks panel */}
      <window.TweaksPanel title="Tweaks · 10HOUSE">
        <window.TweakSection label="Paleta">
          <window.TweakSelect label="Modo" value={t.palette}
          onChange={(v) => setTweak("palette", v)}
          options={[
          { value: "cream", label: "Cream (claro · padrão)" },
          { value: "stone", label: "Stone (warm)" },
          { value: "ivory", label: "Ivory (cool)" },
          { value: "forest", label: "Forest (verde claro)" },
          { value: "onyx", label: "Onyx (escuro)" }]
          } />
          <window.TweakRadio label="Acento" value={t.accent}
          onChange={(v) => setTweak("accent", v)}
          options={[
          { value: "gold", label: "Gold" },
          { value: "bronze", label: "Bronze" },
          { value: "sage", label: "Sage" }]
          } />
        </window.TweakSection>
        <window.TweakSection label="Tipografia">
          <window.TweakSelect label="Display" value={t.displayFont}
          onChange={(v) => setTweak("displayFont", v)}
          options={[
          { value: "Cormorant Garamond", label: "Cormorant Garamond" },
          { value: "Cardo", label: "Cardo" },
          { value: "Tenor Sans", label: "Tenor Sans" }]
          } />
        </window.TweakSection>
      </window.TweaksPanel>
    </>);

}

/* boot */
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
setTimeout(() => {const b = document.getElementById("boot");if (b) b.classList.add("hide");}, 600);
setTimeout(() => {const b = document.getElementById("boot");if (b) b.remove();}, 1300);