// Main page sections. Loaded as Babel script.
// Globals expected: React, COPY, Icon, SectionHeader, CountUp.

const { useState: useState_s, useEffect: useEffect_s, useRef: useRef_s } = React;

// ── Hero ────────────────────────────────────────────────────────────────────
function Hero({ locale, onRegister, onBrochure, dir }) {
  const t = COPY[locale] || COPY.en;
  const h = t.hero;
  const [scrolled, setScrolled] = useState_s(false);
  useEffect_s(() => {
    const on = () => setScrolled(window.scrollY > 40);
    on();
    window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);

  return (
    <header className="hero" id="top">
      <div className="hero-bg">
        <img src="media/project-six-senses-marina-tower.webp" alt="" />
        <div className="hero-scrim"></div>
      </div>

      <div className="hero-ribbon" aria-hidden="true">
        <div className="hero-ribbon-track">
          {Array.from({ length: 4 }).map((_, i) => (
            <span key={i}>
              <em>· {h.tagline} ·</em>
              <em>· Dubai · UK · Europe ·</em>
              <em>· Direct from developer ·</em>
              <em>· Premium waterfront residences ·</em>
            </span>
          ))}
        </div>
      </div>

      <div className="hero-side">
        <span className="hero-side-mark">SG</span>
        <span className="hero-side-rule"></span>
        <span className="hero-side-text">{h.address}</span>
      </div>

      <div className="hero-content">
        <p className="hero-eye">{h.eyebrow}</p>
        <h1 className="hero-h">
          <span className="hero-h-1">{h.title1}</span>
          <span className="hero-h-2">{h.title2}</span>
          <span className="hero-h-3">{h.titleSub}</span>
        </h1>
        <p className="hero-sub">{h.sub}</p>
        <div className="hero-ctas">
          <button className="btn btn--primary btn--lg" onClick={onRegister}>
            {h.cta1}
            <Icon name="arrow-right" size={14} />
          </button>
          <button className="btn btn--ghost btn--lg" onClick={onBrochure}>
            {h.cta2}
          </button>
        </div>
      </div>

      <div className="hero-meta">
        <div className="hero-meta-item">
          <span className="hero-dot"></span>
          <span>{h.status}</span>
        </div>
        <div className="hero-meta-item">
          <Icon name="pin" size={13} />
          <span>{h.address}</span>
        </div>
        <div className="hero-meta-item">
          <span>An IHG branded residence · by Select Group</span>
        </div>
      </div>

      <a href="#facts" className={`hero-scroll ${scrolled ? 'is-hidden' : ''}`} aria-label="Scroll" onClick={(e) => {
        e.preventDefault();
        const el = document.getElementById('facts');
        if (el) window.scrollTo({ top: el.offsetTop - 64, behavior: 'smooth' });
      }}>
        <span className="hero-scroll-line"></span>
        <span className="hero-scroll-label">Scroll</span>
      </a>
    </header>
  );
}

// ── Facts strip ─────────────────────────────────────────────────────────────
function Facts({ locale, showFigures = true }) {
  const t = COPY[locale] || COPY.en;
  const f = t.facts || COPY.en.facts;
  return (
    <section id="facts" className="facts">
      <div className="wrap">
        <div className="facts-head">
          <p className="sect-eye">{f.title}</p>
          <p className="facts-cite">{f.cite}</p>
        </div>
        <div className="facts-grid">
          {f.items.map((it, i) => (
            <div className="fact" key={i}>
              <div className="fact-num">
                {showFigures ? <CountUp target={it.stat} /> : <span>—</span>}
              </div>
              <div className="fact-unit">{it.unit}</div>
              <div className="fact-note">{it.note}</div>
            </div>
          ))}
        </div>
        <div className="facts-pull">
          <span className="facts-pull-q">“</span>
          <p>{f.worldsTallest}</p>
          <p className="facts-pull-cite">{f.worldsTallestCite}</p>
        </div>
      </div>
    </section>
  );
}

// ── Overview ────────────────────────────────────────────────────────────────
function Overview({ locale }) {
  const t = COPY[locale] || COPY.en;
  const o = t.overview || COPY.en.overview;
  return (
    <section id="overview" className="section section--light">
      <div className="wrap">
        <SectionHeader number={o.number} eyebrow={o.eyebrow} heading={o.heading} />
        <div className="overview-grid">
          <div className="overview-body">
            {o.body.map((p, i) => <p key={i}>{p}</p>)}
          </div>
          <dl className="overview-pillars">
            {o.pillars.map((p) => (
              <div key={p.k}>
                <dt>{p.k}</dt>
                <dd>{p.v}</dd>
              </div>
            ))}
          </dl>
        </div>
      </div>
    </section>
  );
}

// ── Location ────────────────────────────────────────────────────────────────
function Location({ locale }) {
  const t = COPY[locale] || COPY.en;
  const l = t.location || COPY.en.location;
  return (
    <section id="location" className="section section--light">
      <div className="wrap">
        <SectionHeader number={l.number} eyebrow={l.eyebrow} heading={l.heading} />
        <div className="loc-grid">
          <div className="loc-image">
            <img src="media/ssm-skydeck-horizon.webp" alt="Marina horizon from the sky deck" loading="lazy" />
            <div className="loc-image-cap">Sky deck · horizon view</div>
          </div>
          <div className="loc-body">
            <p>{l.body}</p>
            <dl className="loc-points">
              {l.points.map((p) => (
                <div key={p.k}>
                  <dt>{p.k}</dt>
                  <dd>{p.v}</dd>
                </div>
              ))}
            </dl>

            {/* Abstract locator — not a real map. Marina coastline as flowing curves. */}
            <figure className="loc-locator" aria-label="Stylised Dubai Marina locator">
              <svg viewBox="0 0 320 200" xmlns="http://www.w3.org/2000/svg">
                <defs>
                  <linearGradient id="locWater" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0" stopColor="#8ED0E8" stopOpacity="0.12"/>
                    <stop offset="1" stopColor="#51A6DC" stopOpacity="0.25"/>
                  </linearGradient>
                </defs>
                <rect x="0" y="0" width="320" height="200" fill="#F7F6F2"/>
                <path d="M0,140 C60,120 100,160 160,140 C220,120 260,160 320,140 L320,200 L0,200 Z" fill="url(#locWater)"/>
                <path d="M0,140 C60,120 100,160 160,140 C220,120 260,160 320,140" stroke="#51A6DC" strokeWidth="0.6" fill="none"/>
                <path d="M40,90 L60,90 L60,150 L40,150 Z M80,70 L100,70 L100,150 L80,150 Z M120,80 L140,80 L140,150 L120,150 Z M180,60 L200,60 L200,150 L180,150 Z M220,100 L240,100 L240,150 L220,150 Z M260,90 L280,90 L280,150 L260,150 Z" fill="#1A1D21" opacity="0.18"/>
                <g>
                  <circle cx="160" cy="150" r="14" fill="none" stroke="#292F68" strokeWidth="0.7" opacity="0.5">
                    <animate attributeName="r" values="6;18;6" dur="3.2s" repeatCount="indefinite"/>
                    <animate attributeName="opacity" values="0.6;0;0.6" dur="3.2s" repeatCount="indefinite"/>
                  </circle>
                  <circle cx="160" cy="150" r="4" fill="#292F68"/>
                  <text x="160" y="178" textAnchor="middle" fontSize="9" fontFamily="Inter,sans-serif" fill="#292F68" letterSpacing="0.08em">SIX SENSES MARINA</text>
                </g>
                <g fill="#6B747E" fontSize="8" fontFamily="Inter,sans-serif" letterSpacing="0.08em">
                  <text x="40" y="60">DUBAI MARINA</text>
                  <text x="220" y="60">JBR · BEACHFRONT</text>
                  <text x="140" y="195" textAnchor="middle" fill="#51A6DC">ARABIAN GULF</text>
                </g>
              </svg>
              <figcaption className="loc-locator-cap">{l.mapNote}</figcaption>
            </figure>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Design & Architecture (full-bleed image with caption block) ─────────────
function Design({ locale }) {
  const t = COPY[locale] || COPY.en;
  const d = t.design || COPY.en.design;
  return (
    <section id="design" className="section section--dark design">
      <div className="design-bg">
        <img src="media/project-six-senses-marina-render2.webp" alt="" loading="lazy" />
        <div className="design-scrim"></div>
      </div>
      <div className="wrap design-content">
        <SectionHeader number={d.number} eyebrow={d.eyebrow} heading={d.heading} className="sect-head--inverse" />
        <p className="design-body">{d.body}</p>
      </div>
    </section>
  );
}

// ── Residences (typology cards) ─────────────────────────────────────────────
function Residences({ locale }) {
  const t = COPY[locale] || COPY.en;
  const r = t.residences || COPY.en.residences;

  // Tiny abstract plan diagrams (suggestive, not real plans)
  const Plan = ({ kind }) => {
    const stroke = '#292F68';
    const s = { fill: 'none', stroke, strokeWidth: 0.8 };
    if (kind === 0) return (
      <svg viewBox="0 0 100 60">
        <rect x="2" y="2" width="96" height="56" {...s}/>
        <line x1="50" y1="2" x2="50" y2="58" {...s}/>
        <line x1="2" y1="30" x2="98" y2="30" {...s}/>
        <line x1="20" y1="30" x2="20" y2="58" {...s}/>
        <line x1="80" y1="2" x2="80" y2="30" {...s}/>
      </svg>
    );
    if (kind === 1) return (
      <svg viewBox="0 0 100 60">
        <rect x="2" y="2" width="96" height="56" {...s}/>
        <line x1="2" y1="22" x2="98" y2="22" {...s}/>
        <line x1="60" y1="22" x2="60" y2="58" {...s}/>
        <line x1="35" y1="22" x2="35" y2="58" {...s}/>
      </svg>
    );
    if (kind === 2) return (
      <svg viewBox="0 0 100 60">
        <rect x="2" y="2" width="96" height="26" {...s}/>
        <rect x="2" y="32" width="96" height="26" {...s}/>
        <line x1="50" y1="2" x2="50" y2="58" {...s} strokeDasharray="2 2"/>
      </svg>
    );
    return (
      <svg viewBox="0 0 100 60">
        <rect x="2" y="2" width="96" height="18" {...s}/>
        <rect x="2" y="21" width="96" height="18" {...s}/>
        <rect x="2" y="40" width="96" height="18" {...s}/>
        <line x1="50" y1="2" x2="50" y2="58" {...s} strokeDasharray="2 2"/>
      </svg>
    );
  };

  return (
    <section id="residences" className="section section--light">
      <div className="wrap">
        <SectionHeader number={r.number} eyebrow={r.eyebrow} heading={r.heading} />
        <p className="sect-lede">{r.body}</p>
        <div className="res-grid">
          {r.types.map((ty, i) => (
            <article className="res-card" key={i}>
              <div className="res-card-plan"><Plan kind={i} /></div>
              <div className="res-card-body">
                <p className="res-card-spec">{ty.spec}</p>
                <h4 className="res-card-name">{ty.name}</h4>
                <p className="res-card-note">{ty.note}</p>
                <div className="res-card-meta">
                  <span>By enquiry</span>
                  <Icon name="arrow-right" size={14} />
                </div>
              </div>
            </article>
          ))}
        </div>
        <p className="res-foot">{r.footnote}</p>
      </div>
    </section>
  );
}

// ── Amenities ───────────────────────────────────────────────────────────────
function Amenities({ locale }) {
  const t = COPY[locale] || COPY.en;
  const a = t.amenities || COPY.en.amenities;
  const images = [
    'ssm-amenity-wellness.webp',
    'ssm-amenity-longevity.webp',
    'ssm-residence-interior.webp',
  ];
  return (
    <section id="amenities" className="section section--cream">
      <div className="wrap">
        <SectionHeader number={a.number} eyebrow={a.eyebrow} heading={a.heading} />
        <p className="sect-lede">{a.body}</p>

        <div className="am-grid">
          <div className="am-images">
            {images.map((src, i) => (
              <figure key={src} className={`am-fig am-fig--${i}`}>
                <img src={`media/${src}`} alt="" loading="lazy" />
              </figure>
            ))}
          </div>
          <ul className="am-list">
            {a.list.map((it, i) => (
              <li key={i}>
                <span className="am-i">{String(i + 1).padStart(2, '0')}</span>
                <div>
                  <h4>{it.t}</h4>
                  <p>{it.d}</p>
                </div>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </section>
  );
}

// ── Gallery (horizontal filmstrip) ──────────────────────────────────────────
function Gallery({ locale }) {
  const t = COPY[locale] || COPY.en;
  const g = t.gallery || COPY.en.gallery;
  const items = [
    { src: 'project-six-senses-marina-tower.webp', cap: 0 },
    { src: 'project-six-senses-marina-render2.webp', cap: 1 },
    { src: 'ssm-skydeck-horizon.webp', cap: 2 },
    { src: 'ssm-amenity-wellness.webp', cap: 3 },
    { src: 'ssm-amenity-longevity.webp', cap: 4 },
    { src: 'ssm-residence-interior.webp', cap: 5 },
  ];
  const scrollerRef = useRef_s(null);
  const [active, setActive] = useState_s(0);

  useEffect_s(() => {
    const el = scrollerRef.current;
    if (!el) return;
    const onScroll = () => {
      const w = el.clientWidth;
      const idx = Math.round(el.scrollLeft / w);
      setActive(idx);
    };
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => el.removeEventListener('scroll', onScroll);
  }, []);

  const go = (dir) => {
    const el = scrollerRef.current;
    if (!el) return;
    el.scrollBy({ left: dir * el.clientWidth, behavior: 'smooth' });
  };

  return (
    <section id="gallery" className="section section--dark gallery">
      <div className="wrap">
        <SectionHeader number={g.number} eyebrow={g.eyebrow} heading={g.heading} className="sect-head--inverse" />
        <div className="gallery-controls">
          <div className="gallery-count">{String(active + 1).padStart(2, '0')} / {String(items.length).padStart(2, '0')}</div>
          <div className="gallery-nav">
            <button onClick={() => go(-1)} aria-label="Previous"><Icon name="arrow-right" size={14} stroke="currentColor" /></button>
            <button onClick={() => go(1)} aria-label="Next"><Icon name="arrow-right" size={14} stroke="currentColor" /></button>
          </div>
        </div>
      </div>
      <div className="gallery-scroller" ref={scrollerRef}>
        {items.map((it, i) => (
          <figure key={it.src} className="gallery-slide">
            <img src={`media/${it.src}`} alt="" loading="lazy" />
            <figcaption>{g.captions[it.cap]}</figcaption>
          </figure>
        ))}
      </div>
      <div className="wrap">
        <p className="gallery-note">{g.note}</p>
      </div>
    </section>
  );
}

// ── Provenance (track record + scale + awards) ──────────────────────────────
function Provenance({ locale, showFigures = true }) {
  const t = COPY[locale] || COPY.en;
  const p = t.provenance || COPY.en.provenance;
  const [showAlt, setShowAlt] = useState_s(false);
  const scale = showAlt ? p.scale.alt : p.scale;

  return (
    <section id="provenance" className="section section--light provenance">
      <div className="wrap">
        <SectionHeader number={p.number} eyebrow={p.eyebrow} heading={p.heading} />
        <div className="prov-intro">
          <p>{p.body}</p>
          <p className="prov-cite">{p.cite}</p>
        </div>

        <ol className="timeline">
          {p.milestones.map((m, i) => (
            <li key={i} className={i === 1 ? 'is-highlight' : ''}>
              <span className="tl-year">{m.y}</span>
              <span className="tl-dot"></span>
              <div className="tl-body">
                <h5>{m.t}</h5>
                <p>{m.d}</p>
              </div>
            </li>
          ))}
        </ol>

        {showFigures && (
          <div className="scale">
            <div className="scale-head">
              <p className="sect-eye">Scale at a glance</p>
              <button className="scale-toggle" onClick={() => setShowAlt(!showAlt)}>
                <span>{p.scale.altLabel}</span>
                <span className={`switch ${showAlt ? 'is-on' : ''}`}><span></span></span>
              </button>
            </div>
            <div className="scale-grid">
              {['a', 'b', 'c'].map((k) => (
                <div className="scale-item" key={k}>
                  <div className="scale-stat"><CountUp target={scale[k].stat} /></div>
                  <div className="scale-unit">{scale[k].unit}</div>
                  <div className="scale-note">{scale[k].note}</div>
                </div>
              ))}
            </div>
          </div>
        )}

        <div className="awards">
          <p className="sect-eye">Awards · verified</p>
          <ul className="awards-list">
            {p.awards.map((aw, i) => (
              <li key={i}>
                <span className="aw-year">{aw.y}</span>
                <div>
                  <h6>{aw.t}</h6>
                  <p>{aw.i}</p>
                </div>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </section>
  );
}

// ── Other launches ──────────────────────────────────────────────────────────
function OtherLaunches({ locale }) {
  const t = COPY[locale] || COPY.en;
  const l = t.launches || COPY.en.launches;
  return (
    <section id="launches" className="section section--cream">
      <div className="wrap">
        <SectionHeader number={l.number} eyebrow={l.eyebrow} heading={l.heading} />
        <div className="launches-grid">
          {l.items.map((it, i) => (
            <a className="launch-card" href="#" key={i}>
              <div className="launch-img">
                <img src={`media/${it.img}`} alt="" loading="lazy" />
              </div>
              <div className="launch-body">
                <h4>{it.t}</h4>
                <p>{it.d}</p>
                <span className="launch-link">View development <Icon name="arrow-right" size={12} /></span>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

// ── Conversion footer ───────────────────────────────────────────────────────
function Conversion({ locale, onSent, onViewing, onBrochure, onBroker }) {
  const t = COPY[locale] || COPY.en;
  const c = t.convert || COPY.en.convert;
  const altActions = [
    { ...c.alt[0], action: onBrochure },
    { ...c.alt[1], action: onViewing },
    { ...c.alt[2], action: () => window.open('https://wa.me/971524596183', '_blank', 'noopener') },
    { ...c.alt[3], action: onBroker },
  ];

  return (
    <section id="convert" className="section section--hero convert">
      <div className="convert-bg">
        <img src="media/cta-waterfront.webp" alt="" loading="lazy" />
        <div className="convert-scrim"></div>
      </div>
      <div className="wrap convert-grid">
        <div className="convert-side">
          <SectionHeader number={c.number} eyebrow={c.eyebrow} heading={c.heading} className="sect-head--inverse" />
          <p className="convert-body">{c.body}</p>
          <ul className="convert-alts">
            {altActions.map((a, i) => (
              <li key={i}>
                <button onClick={a.action}>
                  <div>
                    <h5>{a.t}</h5>
                    <p>{a.d}</p>
                  </div>
                  <Icon name="arrow-right" size={14} />
                </button>
              </li>
            ))}
          </ul>
        </div>
        <div className="convert-form">
          <RegisterForm locale={locale} onSent={onSent} />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  Hero, Facts, Overview, Location, Design, Residences, Amenities,
  Gallery, Provenance, OtherLaunches, Conversion,
});
