/* global React */
const { Button, Badge, StatusDot, Panel, Stat, Tag } = window.OORTDesignSystem_b4ed3c;

/* ---- React-safe lucide icon (no out-of-band DOM mutation) ---- */
function lucideSvg(name, sw) {
  const L = window.lucide;
  if (!L || !L.icons) return '';
  const pascal = String(name).split('-').map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('');
  const node = L.icons[pascal] || L.icons[name];
  if (!node) return '';
  const inner = node.map(([tag, attrs]) =>
    `<${tag} ${Object.entries(attrs).map(([k, v]) => `${k}="${v}"`).join(' ')}></${tag}>`).join('');
  return `<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${sw || 1.6}" stroke-linecap="round" stroke-linejoin="round" class="lucide">${inner}</svg>`;
}
function Icon({ name, sw, className, style }) {
  const html = React.useMemo(() => lucideSvg(name, sw), [name, sw]);
  return <span className={'i ' + (className || '')} style={style} dangerouslySetInnerHTML={{ __html: html }} />;
}

/* ---- brand logomark: an orbital ring + machined notch + core ---- */
function Logomark({ className }) {
  return (
    <svg className={className} viewBox="0 0 32 32" fill="none" aria-hidden="true">
      <circle cx="16" cy="16" r="11" stroke="currentColor" strokeWidth="1.4" />
      <ellipse cx="16" cy="16" rx="14.5" ry="5.4" stroke="currentColor" strokeWidth="1.1"
        opacity="0.7" transform="rotate(-28 16 16)" />
      <circle cx="16" cy="16" r="3.1" fill="currentColor" />
      <path d="M16 1.5V5M30.5 16H27" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
    </svg>
  );
}

/* ---- the hero orbital schematic ---- */
function OrbitViz() {
  return (
    <div className="hero__viz" aria-hidden="true">
      <svg className="viz-svg" viewBox="0 0 500 500">
        <defs>
          <radialGradient id="coreg" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="var(--gold-bright)" />
            <stop offset="60%" stopColor="var(--gold)" />
            <stop offset="100%" stopColor="var(--gold-deep)" />
          </radialGradient>
          <clipPath id="planetclip"><circle cx="250" cy="250" r="248" /></clipPath>
        </defs>

        {/* faint reference rings */}
        <circle cx="250" cy="250" r="240" fill="none" stroke="var(--grid-line-strong)" strokeWidth="1" />
        <circle cx="250" cy="250" r="180" fill="none" stroke="var(--grid-line)" strokeWidth="1" strokeDasharray="2 6" />

        {/* planet arc bottom */}
        <g clipPath="url(#planetclip)">
          <circle cx="250" cy="640" r="430" fill="none" stroke="var(--ion-700)" strokeWidth="2" opacity="0.55" />
          <circle cx="250" cy="640" r="430" fill="rgba(47,227,207,0.04)" />
          <circle cx="250" cy="660" r="430" fill="none" stroke="var(--ion-500)" strokeWidth="1" opacity="0.4" strokeDasharray="3 9" />
        </g>

        {/* tilted orbit ellipse + travelling marker */}
        <g transform="rotate(-22 250 250)">
          <ellipse cx="250" cy="250" rx="208" ry="86" fill="none" stroke="var(--ion-400)" strokeWidth="1.4" opacity="0.7" />
          <circle cx="458" cy="250" r="4" fill="var(--ion-400)" />
        </g>

        {/* the station — rotating ring assembly */}
        <g className="viz-ring-spin">
          <circle cx="250" cy="250" r="120" fill="none" stroke="var(--gold)" strokeWidth="2.5" />
          <circle cx="250" cy="250" r="120" fill="none" stroke="var(--gold-bright)" strokeWidth="2.5"
            strokeDasharray="6 28" opacity="0.9" />
          {[0, 45, 90, 135, 180, 225, 270, 315].map((a) => (
            <line key={a} x1="250" y1="250"
              x2={250 + 120 * Math.cos((a * Math.PI) / 180)}
              y2={250 + 120 * Math.sin((a * Math.PI) / 180)}
              stroke="var(--gold-line)" strokeWidth="1" />
          ))}
          {[0, 90, 180, 270].map((a) => (
            <rect key={a} x={250 + 110 * Math.cos((a * Math.PI) / 180) - 7}
              y={250 + 110 * Math.sin((a * Math.PI) / 180) - 7}
              width="14" height="14" rx="2" fill="var(--surface-panel)" stroke="var(--gold)" strokeWidth="1.4" />
          ))}
        </g>

        {/* inner counter-rotating hub */}
        <g className="viz-ring-spin rev">
          <circle cx="250" cy="250" r="64" fill="none" stroke="var(--gold-line)" strokeWidth="1.4" strokeDasharray="3 7" />
          <circle cx="250" cy="186" r="3" fill="var(--gold)" />
        </g>

        {/* core */}
        <circle className="viz-core" cx="250" cy="250" r="20" fill="url(#coreg)" />
        <circle className="viz-core" cx="250" cy="250" r="32" fill="none" stroke="var(--gold)" strokeWidth="1" opacity="0.5" />

        {/* HUD crosshair ticks */}
        {[[250, 16], [250, 484], [16, 250], [484, 250]].map(([x, y], i) => (
          <line key={i} x1={x} y1={y}
            x2={i < 2 ? x : x + (i === 2 ? 14 : -14)}
            y2={i < 2 ? y + (i === 0 ? 14 : -14) : y}
            stroke="var(--steel-300)" strokeWidth="1.4" strokeLinecap="round" />
        ))}
      </svg>
    </div>
  );
}

/* ============================================================ */
function Nav({ onApply }) {
  return (
    <nav className="nav">
      <div className="nav__in">
        <a className="brand" href="#top">
          <Logomark className="brand__mark" />
          <span className="brand__name">ZHOSS ORBITAL</span>
          <span className="brand__sub">The Palace</span>
        </a>
        <div className="nav__links">
          <a href="#residence">The residence</a>
          <a href="#membership">Membership</a>
          <a href="#founder">The Founder</a>
          <a href="#discretion">Discretion</a>
        </div>
        <div className="nav__cta">
          <Button variant="primary" size="sm" className="lux" onClick={onApply}>Apply for a berth</Button>
        </div>
      </div>
    </nav>
  );
}

function Hero({ onApply }) {
  const chips = [
    ['ALTITUDE', '412', 'km'],
    ['JURISDICTION', 'none', ''],
    ['DISCRETION', 'nominal', ''],
    ['GRAVITY', 'optional', ''],
  ];
  return (
    <header className="hero wrap" id="top">
      <div className="hero__grid">
        <div>
          <div className="hero__kicker">
            <span className="eyebrow">// Low Earth orbit · Est. 2029</span>
          </div>
          <h1>Your private orbital <span className="lux-word">fuck-palace.</span> Finally in range.</h1>
          <p className="hero__lead">
            412 kilometres up, ZHOSS ORBITAL operates the first members-only pleasure
            residence rated for continuous human occupancy. Whatever you once flew to a
            private island for — bring it aboard. No coastline, no manifest, no
            jurisdiction, and no one left to raid it.
          </p>
          <div className="hero__actions">
            <Button variant="primary" size="lg" className="lux" onClick={onApply}>Apply for a berth</Button>
            <Button variant="secondary" size="lg" onClick={() => scrollTo('residence')}>Tour the residence</Button>
          </div>
          <div className="hero__chips">
            {chips.map(([k, v, u]) => (
              <span className="chip" key={k}>
                {k} <b>{v}</b>{u ? <span className="u">{u}</span> : null}
              </span>
            ))}
          </div>
        </div>
        <OrbitViz />
      </div>
    </header>
  );
}

function StatBand() {
  const cells = [
    ['412', 'km', 'Orbital altitude'],
    ['16', '/day', 'Scheduled sunrises'],
    ['3 : 1', '', 'Crew-to-guest ratio'],
    ['0', '', 'Warrants with standing'],
  ];
  return (
    <section className="statband">
      <div className="statband__in">
        {cells.map(([v, u, l]) => (
          <div className="statcell" key={l}>
            <div className="statcell__v">{v}{u ? <span className="u">{u}</span> : null}</div>
            <div className="statcell__l">{l}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

function Amenities() {
  const items = [
    ['orbit', 'The zero-G primary suite', 'A nine-metre weightless chamber with active climate, mood-mapped lighting, a viewport the width of a continent, and a hatch that seals from the inside.'],
    ['sunrise', 'Eternal golden hour', 'Sixteen sunrises a day — scheduled, looped, or skipped entirely. Whatever mood the evening calls for, the Palace holds the light there.'],
    ['wine', 'Observation-deck dining', 'A private galley and a flight-rated sommelier crew, plated against the live curvature of the Earth. Plus-ones are catered for, and uncounted.'],
    ['shield-check', 'Absolute discretion', 'No manifest. No flight log. No downlink. Whoever you arrive with, and whatever you get up to, never officially happened.'],
    ['rotate-3d', 'Recreational gravity', 'Spin the ring up to 0.4 g for the evening, or cut it to nothing. Every appetite behaves differently in freefall — the Palace was engineered for all of them.'],
    ['concierge-bell', 'Companionship, arranged', 'A discreet concierge handles introductions and itineraries on request. Three attendants per guest, trained equally in hospitality and in forgetting faces.'],
  ];
  return (
    <section className="section wrap" id="residence">
      <div className="section-head">
        <span className="eyebrow">// The residence</span>
        <h2>Engineered for indulgence. Rated for orbit.</h2>
        <p>Everything the old arrangements offered — the privacy, the company, the deniability — rebuilt at altitude, where no coastline can be photographed and no warrant has standing.</p>
      </div>
      <div className="amen-grid">
        {items.map(([icon, h, p]) => (
          <Panel key={h} className="amen" ticks>
            <span className="amen__icon"><Icon name={icon} /></span>
            <h3>{h}</h3>
            <p>{p}</p>
          </Panel>
        ))}
      </div>
    </section>
  );
}

function Tiers({ onApply }) {
  const tiers = [
    {
      name: 'Cuck Airlock', price: '$2.4M', per: '/ yr', feature: false,
      desc: 'A foothold in orbit for the merely rich — close enough to watch, never close enough to touch.',
      cta: 'Apply', variant: 'secondary',
      feats: ['Shared berth, 14 nights / yr', 'Communal observation deck', 'Standard discretion protocol', 'Return shuttle included', '0.4 g recreation, by reservation'],
    },
    {
      name: 'Breeder Berth', price: '$18M', per: '/ yr', feature: true, tag: 'Most chosen',
      desc: 'A private suite, a vetted match, and a crew that logs nothing — continue the line where no surface can reach it.',
      cta: 'Apply', variant: 'primary',
      feats: ['Private suite, 90 nights / yr', 'Priority docking window', 'Dedicated crew of two', 'NDA-grade discretion', 'Heir-grade gravity scheduling'],
    },
    {
      name: "Founder's Circle", price: 'By bloodline', per: '', feature: false, gold: true,
      desc: 'For the legacy-minded. The ring keeps your name so the planet is obliged to.',
      cta: 'Petition the Circle', variant: 'secondary',
      feats: ['Hereditary berth, willed in perpetuity', 'A ring section that bears your name', 'Your likeness on the observation deck', 'Heirs pre-cleared at birth', 'A dynasty no jurisdiction can reach'],
    },
  ];
  return (
    <section className="section wrap" id="membership">
      <div className="section-head">
        <span className="eyebrow">// Membership</span>
        <h2>Three ways to leave the planet.</h2>
        <p>Pricing is annual and non-negotiable. Applications are reviewed personally by the Founder. Most are declined.</p>
      </div>
      <div className="tiers">
        {tiers.map((t) => (
          <div className={'tier' + (t.feature ? ' is-feature' : '')} key={t.name}>
            {t.tag ? <span className="tier__tag">{t.tag}</span> : null}
            <div className={'tier__name' + (t.gold ? ' gold' : '')}>{t.name}</div>
            <div className={'tier__price' + (t.per ? '' : ' text')}>{t.price} {t.per ? <small>{t.per}</small> : null}</div>
            <p className="tier__desc">{t.desc}</p>
            <ul className="tier__feats">
              {t.feats.map((f) => (
                <li key={f}><Icon name="check" />{f}</li>
              ))}
            </ul>
            <Button variant={t.variant} className={t.gold || t.feature ? 'lux' : ''} onClick={onApply}>{t.cta}</Button>
          </div>
        ))}
      </div>
    </section>
  );
}

function Founder() {
  return (
    <section className="section wrap" id="founder">
      <div className="founder">
        <div className="founder__portrait">
          <image-slot id="founder-portrait" shape="rounded" radius="6"
            src="founder.webp"
            placeholder="Drop the Founder's portrait"></image-slot>
        </div>
        <div>
          <span className="eyebrow">// The Founder</span>
          <p className="founder__quote">
            "I sold the planet everything it could carry. Then I built the one
            address left where no coastline gets photographed and no one can
            follow. <span className="g">This.</span> And I kept the best ring for
            myself."
          </p>
          <div className="founder__by">
            <span className="ln"></span>
            <span><b>B. Zhoss</b> — Founder &amp; Resident-in-Chief, ZHOSS ORBITAL</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function Testimonials() {
  const cards = [
    ['I cancelled the superyacht and the doomsday bunker. You can’t out-sail a subpoena — but you can absolutely out-orbit one.', 'Verified guest', 'declined to be identified'],
    ['Everything the island used to be — the company, the privacy, the deniability — minus the part where it gets raided on a Tuesday.', "Founder's Suite holder", 'you’d know the firm'],
    ['My lawyers said never put it in writing. Up here there’s nothing to write on, no one to write to, and no one taking the call.', 'Anonymous', 'Ring 3 · 0.0 g'],
  ];
  return (
    <section className="section wrap" id="word">
      <div className="section-head">
        <span className="eyebrow">// Word from orbit</span>
        <h2>The reviews are in. The reviewers aren’t.</h2>
        <p>Our guests tend to be between obligations — their old destinations having become, regrettably, evidence. Names are withheld. The relief, they insisted, was not.</p>
      </div>
      <figure className="tm-featured">
        <span className="tm-mark">“</span>
        <blockquote>Waaay better than a certain New York financier’s island. <span className="g">No flight logs, no little black book, no guest list anyone can subpoena</span> — and the view actually goes somewhere.</blockquote>
        <figcaption className="tm-by"><span className="ln"></span><span><b>Resident, Ring 2</b> — name withheld, naturally</span></figcaption>
      </figure>
      <div className="tm-grid">
        {cards.map(([q, who, sub]) => (
          <figure className="tm-card" key={who + sub}>
            <span className="tm-mark">“</span>
            <blockquote>{q}</blockquote>
            <figcaption className="tm-by"><span className="ln"></span><span><b>{who}</b> · {sub}</span></figcaption>
          </figure>
        ))}
      </div>
    </section>
  );
}

function CtaBand({ onApply }) {
  return (
    <section className="ctaband wrap" id="discretion">
      <span className="eyebrow">// Boarding</span>
      <h2>The airlock is open.</h2>
      <p>Applications take about three minutes and are reviewed personally. Bring liquidity and discretion; leave the paper trail, the lawyers, and the manifest on the ground — up here, there isn’t one.</p>
      <Button variant="primary" size="lg" className="lux" onClick={onApply}>Begin your application</Button>
    </section>
  );
}

function Footer() {
  return (
    <footer className="foot">
      <div className="wrap">
        <div className="foot__in">
          <a className="brand" href="#top">
            <Logomark className="brand__mark" />
            <span className="brand__name">ZHOSS ORBITAL</span>
          </a>
          <div className="foot__links">
            <a href="#residence">The residence</a>
            <a href="#membership">Membership</a>
            <a href="#founder">The Founder</a>
            <a href="#">Discretion policy</a>
            <a href="#">Manifest (none)</a>
            <a href="#">Re-entry terms</a>
          </div>
        </div>
        <p className="foot__fine">
          ZHOSS ORBITAL and "The Palace" are a fictional luxury habitat created for satire. No berths exist, no orbit is for sale, and no real person is depicted or endorsed. Do not attempt to reach low Earth orbit. © 2029 Zhoss Orbital Holdings — all sunrises reserved.
        </p>
      </div>
    </footer>
  );
}

function scrollTo(id) {
  const el = document.getElementById(id);
  if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 64, behavior: 'smooth' });
}

function Landing({ onApply }) {
  return (
    <div>
      <Nav onApply={onApply} />
      <Hero onApply={onApply} />
      <StatBand />
      <Amenities />
      <Tiers onApply={onApply} />
      <Founder />
      <Testimonials />
      <CtaBand onApply={onApply} />
      <Footer />
    </div>
  );
}

Object.assign(window, { Landing, Icon });
