// House of Noey — shared components (header, ticker, scroll progress, footer, press, modal)
const { useState, useEffect, useRef, useCallback, useMemo } = React;

// ——— Scroll progress bar ———
function ScrollProgress() {
  const [pct, setPct] = useState(0);
  useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement;
      const max = h.scrollHeight - h.clientHeight;
      setPct(max > 0 ? (h.scrollTop / max) * 100 : 0);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return <div className="scroll-progress" style={{ width: `${pct}%` }} />;
}

// ——— Language toggle (EN / 中文 / 日本語 / TH) ———
function LangToggle({ lang, setLang }) {
  const langs = [
    { code: "en", label: "EN", cls: "" },
    { code: "ja", label: "日本語", cls: "lang--ja" },
    { code: "zh", label: "中文", cls: "lang--zh" },
    { code: "th", label: "TH", cls: "" }
  ];
  return (
    <div className="lang" role="tablist" aria-label="Language">
      {langs.map(l => (
        <button
          key={l.code}
          className={l.cls}
          data-active={lang === l.code}
          onClick={() => setLang(l.code)}
          aria-selected={lang === l.code}
        >
          {l.label}
        </button>
      ))}
    </div>
  );
}

// ——— Top nav ———
function Header({ lang, setLang, t, onBook }) {
  const contact = window.HON_CONTACT || {};
  return (
    <nav className="nav">
      <div className="shell nav__inner">
        <a href="#top" className="wordmark" aria-label="House of Noey">
          <span className="wordmark__house">House of</span>
          <span className="wordmark__noey">Noey</span>
        </a>
        <div className="nav__links">
          <a href="#essay">{t.nav.neighborhoods}</a>
          <a href="#listings">{t.nav.forSale}</a>
          <a href="#essay">{t.nav.journal}</a>
          <a href="#about">{t.nav.about}</a>
          <a href="#booking" onClick={(e) => { e.preventDefault(); onBook && onBook(); }}>{t.nav.contact}</a>
        </div>
        <div className="nav-social" aria-label="Social channels">
          <a href="https://instagram.com/noeyrealestate" target="_blank" rel="noopener" aria-label="Instagram">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" aria-hidden="true">
              <rect x="3" y="3" width="18" height="18" rx="5"/>
              <circle cx="12" cy="12" r="4"/>
              <circle cx="17.5" cy="6.5" r="1" fill="currentColor"/>
            </svg>
          </a>
          <a href="https://tiktok.com/@noeyrealestate" target="_blank" rel="noopener" aria-label="TikTok">
            <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
              <path d="M16 3v3a4 4 0 0 0 4 4v3a7 7 0 0 1-4-1.3V16a5 5 0 1 1-5-5v3a2 2 0 1 0 2 2V3z"/>
            </svg>
          </a>
          <a href={contact.lineUrl || "https://line.me/R/ti/p/@noeyrealestate"} target="_blank" rel="noopener" aria-label="LINE">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
              <path d="M5.5 17.5c-1.9-1.4-3-3.3-3-5.5 0-4.4 4.5-8 10-8s10 3.6 10 8-4.5 8-10 8c-.9 0-1.8-.1-2.6-.3L5.5 21v-3.5z"/>
              <path d="M7.2 9.5v4h2.1M10.7 9.5v4M12.4 13.5v-4l2.7 4v-4M17.2 9.5h2.3M17.2 11.5h1.9M17.2 13.5h2.4"/>
            </svg>
          </a>
        </div>
        <LangToggle lang={lang} setLang={setLang} />
      </div>
    </nav>
  );
}

// ——— Market ticker ———
function Ticker({ items }) {
  const doubled = [...items, ...items, ...items];
  return (
    <div className="ticker" aria-hidden="true">
      <div className="ticker__track">
        {doubled.map((it, i) => (
          <span key={i}>
            <span className="muted">{it.l}</span>{"  "}
            <strong className={it.tone}>{it.v}</strong>
          </span>
        ))}
      </div>
    </div>
  );
}

// ——— Reveal-on-scroll wrapper ———
function Reveal({ children, delay = 0, as: Tag = "div", className = "", ...rest }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(
      (entries) => entries.forEach(e => {
        if (e.isIntersecting) { setSeen(true); io.disconnect(); }
      }),
      { threshold: 0.12, rootMargin: "0px 0px -80px 0px" }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return (
    <Tag
      ref={ref}
      className={`reveal ${seen ? "is-in" : ""} ${className}`}
      style={{ transitionDelay: `${delay}ms` }}
      {...rest}
    >
      {children}
    </Tag>
  );
}

// ——— Press strip ———
function Press({ t }) {
  return (
    <section className="section section--surface" style={{ paddingTop: 60, paddingBottom: 60 }}>
      <div className="shell">
        <div className="eyebrow center" style={{ marginBottom: 28 }}>{t.press.eyebrow}</div>
        <div className="press">
          <div className="press__logo">Tatler Asia</div>
          <div className="press__logo bold">BANGKOK POST</div>
          <div className="press__logo cap">Monocle</div>
          <div className="press__logo bold">PropertyGuru</div>
          <div className="press__logo">Sotheby's</div>
        </div>
      </div>
    </section>
  );
}

// ——— Map + Districts (flat editorial SVG) ———
function DistrictMap({ t }) {
  const [activeIdx, setActiveIdx] = useState(0);
  const districts = (window.I18N.en.map.districts).map((d, i) => ({
    ...d, active: i === activeIdx
  }));
  const Hover = (i) => () => setActiveIdx(i);
  return (
    <div className="map-wrap">
      <Reveal className="map" delay={80}>
        <svg viewBox="0 0 800 600" xmlns="http://www.w3.org/2000/svg" aria-label="Bangkok districts map">
          <defs>
            <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
              <path d="M 40 0 L 0 0 0 40" fill="none" stroke="rgba(26,20,16,0.06)" strokeWidth="0.5"/>
            </pattern>
            <pattern id="diag" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
              <line x1="0" y1="0" x2="0" y2="6" stroke="rgba(184,151,74,0.35)" strokeWidth="1"/>
            </pattern>
          </defs>
          <rect width="800" height="600" fill="url(#grid)" />
          {/* Chao Phraya river curve */}
          <path d="M 60 60 C 120 200, 80 340, 180 420 S 320 540, 420 580"
                stroke="rgba(184,151,74,0.5)" strokeWidth="22" fill="none" strokeLinecap="round" opacity="0.35"/>
          <path d="M 60 60 C 120 200, 80 340, 180 420 S 320 540, 420 580"
                stroke="rgba(26,20,16,0.4)" strokeWidth="1" fill="none" strokeLinecap="round" strokeDasharray="2 4"/>
          {/* BTS lines */}
          <line x1="120" y1="500" x2="720" y2="120" stroke="rgba(196,98,58,0.35)" strokeWidth="2"/>
          <line x1="200" y1="80" x2="640" y2="540" stroke="rgba(26,20,16,0.2)" strokeWidth="1" strokeDasharray="4 4"/>

          {/* District 1: Sathorn */}
          <g style={{cursor:"pointer"}} onMouseEnter={Hover(0)}>
            <rect x="220" y="320" width="190" height="170"
                  fill={activeIdx===0?"url(#diag)":"rgba(184,151,74,0.10)"}
                  stroke={activeIdx===0?"#B8974A":"rgba(184,151,74,0.4)"}
                  strokeWidth={activeIdx===0?2:1}/>
            <text x="315" y="410" textAnchor="middle" fontFamily="Cormorant Garamond" fontSize="22" fill="#1A1410">Sathorn</text>
            <text x="315" y="430" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="0.15em" fill="#6B5E50">01</text>
          </g>

          {/* District 2: Sukhumvit */}
          <g style={{cursor:"pointer"}} onMouseEnter={Hover(1)}>
            <rect x="430" y="240" width="280" height="160"
                  fill={activeIdx===1?"url(#diag)":"rgba(184,151,74,0.10)"}
                  stroke={activeIdx===1?"#B8974A":"rgba(184,151,74,0.4)"}
                  strokeWidth={activeIdx===1?2:1}/>
            <text x="570" y="320" textAnchor="middle" fontFamily="Cormorant Garamond" fontSize="22" fill="#1A1410">Sukhumvit</text>
            <text x="570" y="340" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="0.15em" fill="#6B5E50">02</text>
          </g>

          {/* District 3: Ari */}
          <g style={{cursor:"pointer"}} onMouseEnter={Hover(2)}>
            <rect x="280" y="100" width="160" height="130"
                  fill={activeIdx===2?"url(#diag)":"rgba(184,151,74,0.10)"}
                  stroke={activeIdx===2?"#B8974A":"rgba(184,151,74,0.4)"}
                  strokeWidth={activeIdx===2?2:1}/>
            <text x="360" y="170" textAnchor="middle" fontFamily="Cormorant Garamond" fontSize="22" fill="#1A1410">Ari</text>
            <text x="360" y="190" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="0.15em" fill="#6B5E50">03</text>
          </g>

          {/* District 4: Riverside */}
          <g style={{cursor:"pointer"}} onMouseEnter={Hover(3)}>
            <rect x="80" y="380" width="130" height="160"
                  fill={activeIdx===3?"url(#diag)":"rgba(184,151,74,0.10)"}
                  stroke={activeIdx===3?"#B8974A":"rgba(184,151,74,0.4)"}
                  strokeWidth={activeIdx===3?2:1}/>
            <text x="145" y="450" textAnchor="middle" fontFamily="Cormorant Garamond" fontSize="20" fill="#1A1410">Riverside</text>
            <text x="145" y="470" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="0.15em" fill="#6B5E50">04</text>
          </g>

          {/* BTS pins */}
          {[
            { x: 320, y: 360, l: "Chong Nonsi" },
            { x: 540, y: 270, l: "Phrom Phong" },
            { x: 340, y: 150, l: "Ari" },
            { x: 150, y: 460, l: "Saphan Taksin" }
          ].map((p, i) => (
            <g key={i}>
              <circle cx={p.x} cy={p.y} r="4" fill="#C4623A"/>
              <circle cx={p.x} cy={p.y} r="9" fill="none" stroke="#C4623A" strokeWidth="0.5" opacity="0.5"/>
              <text x={p.x + 12} y={p.y + 4} fontFamily="JetBrains Mono" fontSize="9" fill="#6B5E50" letterSpacing="0.1em">{p.l}</text>
            </g>
          ))}

          {/* Compass */}
          <g transform="translate(720,80)">
            <circle r="22" fill="none" stroke="rgba(26,20,16,0.2)"/>
            <path d="M 0 -14 L 4 0 L 0 14 L -4 0 Z" fill="#B8974A"/>
            <text y="-26" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="0.2em" fill="#6B5E50">N</text>
          </g>
        </svg>
      </Reveal>

      <div className="district-list">
        {districts.map((d, i) => (
          <div key={d.n} className="district" data-active={d.active} onMouseEnter={Hover(i)}>
            <div className="district__num">{d.n}</div>
            <div>
              <div className="district__name">
                {d.name}
                <small>{d.bts}</small>
              </div>
            </div>
            <div className="district__yield" style={{fontFamily:"var(--f-mono)", fontSize:11, letterSpacing:"0.06em", color:"var(--ink-sec)"}}>
              {d.bts.split("·")[0].trim()}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ——— Neighborhood marquee strip (dark, big serif) ———
function NeighborhoodStrip() {
  const names = [
    { n: "Sathorn", sup: "01" },
    { n: "Sukhumvit", sup: "02", em: true },
    { n: "Ari", sup: "03" },
    { n: "Riverside", sup: "04", em: true },
    { n: "Phrom Phong", sup: "05" },
    { n: "Thong Lo", sup: "06", em: true },
    { n: "Ekkamai", sup: "07" }
  ];
  const doubled = [...names, ...names];
  return (
    <div className="neigh-strip" aria-hidden="true">
      <div className="neigh-strip__track">
        {doubled.map((n, i) => (
          <span key={i} className="neigh-strip__item">
            {n.em ? <em>{n.n}</em> : n.n}
            <sup>·&nbsp;{n.sup}</sup>
            <span className="neigh-strip__star">✦</span>
          </span>
        ))}
      </div>
    </div>
  );
}

// ——— Practice — editorial 3-step "how working together unfolds" + quote ———
function Practice() {
  return (
    <section className="section" id="practice">
      <div className="shell">
        <div className="section__head">
          <div>
            <div className="section__num">04 / Practice</div>
            <Reveal as="h2" className="section__title">How working together unfolds.</Reveal>
          </div>
          <Reveal as="p" className="section__intro" delay={120}>
            No funnels. No forms after the first reply. Three steps; the last one is a building. If we are not the right fit, I will tell you on the first morning and recommend a colleague I trust by name.
          </Reveal>
        </div>

        <div className="practice-grid">
          <Reveal className="practice-card" delay={0}>
            <span className="practice-card__step">§ I</span>
            <h3 className="practice-card__title">The coffee.</h3>
            <div className="practice-card__time">30 minutes · at a soi you choose</div>
            <p>We meet at the neighborhood you are curious about. You bring the questions; I bring the morning. We decide whether what you want actually exists in Bangkok, and whether I am the right person to find it.</p>
            <div className="practice-card__rule"></div>
            <div className="practice-card__meta">
              <span>Cost</span><strong>Complimentary</strong>
              <span>Location</span><strong>Bangkok · in person</strong>
            </div>
          </Reveal>

          <Reveal className="practice-card" delay={120}>
            <span className="practice-card__step">§ II</span>
            <h3 className="practice-card__title">The walk.</h3>
            <div className="practice-card__time">90–120 minutes · two or three buildings</div>
            <p>A morning together. I show you the lift, the lobby at seven, the parking ratio in person. The buildings I disqualify on the walk matter as much as the ones I do not — most clients leave with a shorter list, not a longer one.</p>
            <div className="practice-card__rule"></div>
            <div className="practice-card__meta">
              <span>When</span><strong>Tue–Sat · 07:00</strong>
              <span>You bring</span><strong>Walking shoes</strong>
            </div>
          </Reveal>

          <Reveal className="practice-card" delay={240}>
            <span className="practice-card__step">§ III</span>
            <h3 className="practice-card__title">The file.</h3>
            <div className="practice-card__time">A one-page brief · sent via LINE</div>
            <p>A single page: the building's name, the floor plate, the management history, the trade-offs in plain language. You decide. If you proceed, I handle the negotiation. If not, the file is yours to keep.</p>
            <div className="practice-card__rule"></div>
            <div className="practice-card__meta">
              <span>Delivered</span><strong>LINE · within 48h</strong>
              <span>Format</span><strong>One page · PDF</strong>
            </div>
          </Reveal>
        </div>

        {/* Testimonial — single, specific, unsalesy */}
        <div className="testimonial">
          <div className="testimonial__mark">"</div>
          <Reveal as="blockquote" className="testimonial__quote">
            Noey turned us down twice before she agreed to walk Sathorn with us.
            We bought the third building she showed and have not regretted a Sunday morning since.
          </Reveal>
          <div className="testimonial__foot">
            <div className="testimonial__person">
              <div className="testimonial__name">A. Tanaka</div>
              <div className="testimonial__role">Tokyo / Sathorn · client since 2024</div>
            </div>
            <div className="testimonial__nav">
              <button aria-label="previous">‹</button>
              <span>01 / 04</span>
              <button aria-label="next">›</button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ——— Footer ———
function Footer({ t }) {
  const en = window.I18N.en;
  const contact = window.HON_CONTACT || {};
  return (
    <footer className="footer">
      <div className="shell">
        <div className="footer__grid">
          <div className="footer__brand">
            <a className="wordmark" href="#top">
              <span className="wordmark__house">House of</span>
              <span className="wordmark__noey">Noey</span>
            </a>
            <p className="footer__tagline">{t.footer.tagline}</p>
            <p className="footer__identity">Private advisory by Natcha Wiriyaporn, known to clients as Noey.</p>
            <div style={{ marginTop: 28, display: "flex", gap: 14, alignItems: "center" }}>
              <a href="https://instagram.com/noeyrealestate" target="_blank" rel="noopener" aria-label="Instagram"
                 style={{ width: 36, height: 36, borderRadius: "50%", border: "1px solid rgba(250,247,242,0.2)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                  <rect x="3" y="3" width="18" height="18" rx="5"/>
                  <circle cx="12" cy="12" r="4"/>
                  <circle cx="17.5" cy="6.5" r="1" fill="currentColor"/>
                </svg>
              </a>
              <a href="https://tiktok.com/@noeyrealestate" target="_blank" rel="noopener" aria-label="TikTok"
                 style={{ width: 36, height: 36, borderRadius: "50%", border: "1px solid rgba(250,247,242,0.2)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M16 3v3a4 4 0 0 0 4 4v3a7 7 0 0 1-4-1.3V16a5 5 0 1 1-5-5v3a2 2 0 1 0 2 2V3z"/>
                </svg>
              </a>
              <a href={contact.lineUrl || "https://line.me/R/ti/p/@noeyrealestate"} target="_blank" rel="noopener" aria-label="LINE"
                 style={{ width: 36, height: 36, borderRadius: "50%", border: "1px solid rgba(250,247,242,0.2)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--f-mono)", fontSize: 10, letterSpacing: "0.1em" }}>LINE</a>
            </div>
          </div>

          <div className="footer__col">
            <h5>{en.footer.colTitles[0]}</h5>
            <ul>
              {en.footer.col1.map(l => <li key={l}><a href="#essay">{l}</a></li>)}
            </ul>
          </div>
          <div className="footer__col">
            <h5>{en.footer.colTitles[1]}</h5>
            <ul>
              {en.footer.col2.map(l => <li key={l}><a href="#">{l}</a></li>)}
            </ul>
          </div>
          <div className="footer__col">
            <h5>{en.footer.colTitles[2]}</h5>
            <ul>
              {en.footer.col3.map(l => <li key={l}><a href="#">{l}</a></li>)}
              <li><a href="brand-book.html">Brand Book</a></li>
              <li><a href="design-template.html">Design Template</a></li>
              <li><a href="admin.html">Admin</a></li>
            </ul>
          </div>
        </div>
        <div className="footer__bottom">
          <div>{t.footer.meta}</div>
          <div>HOUSE OF NOEY · BANGKOK 10120 · TH</div>
        </div>
      </div>
    </footer>
  );
}

// ——— Mobile bottom-tab nav (shown < 900px) ———
function MobileNav({ t, onBook }) {
  const tabs = [
    { id: "essay",   label: t.nav.journal,      icon: "§" },
    { id: "listings",label: t.nav.forSale,      icon: "▢" },
    { id: "booking", label: t.nav.contact,      icon: "✦" }
  ];
  const go = (id, e) => {
    e.preventDefault();
    if (id === "booking" && onBook) { onBook(); return; }
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });
  };
  return (
    <nav className="mob-nav" aria-label="Sections">
      {tabs.map(tab => (
        <a key={tab.id} href={`#${tab.id}`} onClick={(e) => go(tab.id, e)} className="mob-nav__tab">
          <span className="mob-nav__icon" aria-hidden="true">{tab.icon}</span>
          <span className="mob-nav__label">{tab.label}</span>
        </a>
      ))}
    </nav>
  );
}

// Export shared components to window
Object.assign(window, {
  ScrollProgress, LangToggle, Header, Ticker, Reveal,
  Press, DistrictMap, NeighborhoodStrip, Practice, MobileNav, Footer
});
