/* global React, ReactDOM */
const { useState, useEffect, useRef } = React;

/* --------------------------------------------------------------
   misilab.com — app v3 (impeccable pass: distill, typeset,
   delight, animate). Mobile-first. Editorial restraint.
   -------------------------------------------------------------- */

const DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "system",
  "hero": "editorial",
  "accent": "subtle",
  "ticker": "marquee",
  "tracker": "shovel",
  "rowStyle": "card",
  "moodIntensity": 1
} /*EDITMODE-END*/;

/* ---------- TIME TICKER ---------- */
const CITIES = [
  { code: 'AMS', tz: 'Europe/Amsterdam' },
  { code: 'JKT', tz: 'Asia/Jakarta' },
  { code: 'SGP', tz: 'Asia/Singapore' },
  { code: 'TYO', tz: 'Asia/Tokyo' }
];

function formatCity(tz) {
  try {
    return new Intl.DateTimeFormat('en-GB', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: tz }).format(new Date());
  } catch (e) { return '--:--'; }
}

function Ticker() {
  const [, tick] = useState(0);
  useEffect(() => { const id = setInterval(() => tick((v) => v + 1), 30000); return () => clearInterval(id); }, []);

  const items = CITIES.map((c) => ({ code: c.code, time: formatCity(c.tz) }));
  // Duplicate for seamless loop and wider desktop spacing
  const looped = [...items, ...items, ...items, ...items];

  return (
    <div className="ticker" aria-label="Current time across our cities">
      <div className="ticker-track">
        {looped.map((it, i) =>
          <span key={i} className="ticker-item">
            <span className="city">{it.code}</span>
            <span className="time">{it.time}</span>
            <span className="ticker-sep">·</span>
          </span>
        )}
      </div>
    </div>);
}

/* ---------- ICONS ---------- */
const IcInstagram = () =>
  <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
    <rect x="3.5" y="3.5" width="17" height="17" rx="5" stroke="currentColor" strokeWidth="1.6" />
    <circle cx="12" cy="12" r="3.6" stroke="currentColor" strokeWidth="1.6" />
    <circle cx="17.2" cy="6.8" r="1" fill="currentColor" />
  </svg>;

const IcTikTok = () =>
  <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
    <path d="M14 3v10.5a3.5 3.5 0 1 1-3.5-3.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
    <path d="M14 3c.4 2.4 2 4.2 4.5 4.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
  </svg>;

const IcYouTube = () =>
  <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
    <rect x="2.5" y="6" width="19" height="12" rx="3" stroke="currentColor" strokeWidth="1.6" />
    <path d="M10.5 9.5v5l4.2-2.5-4.2-2.5z" fill="currentColor" />
  </svg>;

const IcGlobe = () =>
  <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
    <circle cx="12" cy="12" r="8.5" stroke="currentColor" strokeWidth="1.6" />
    <path d="M3.5 12h17M12 3.5c2.5 2.5 3.8 5.5 3.8 8.5s-1.3 6-3.8 8.5M12 3.5c-2.5 2.5-3.8 5.5-3.8 8.5s1.3 6 3.8 8.5" stroke="currentColor" strokeWidth="1.4" />
  </svg>;

const IcMail = () =>
  <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
    <rect x="3" y="5.5" width="18" height="13" rx="2.5" stroke="currentColor" strokeWidth="1.6" />
    <path d="M3.8 7l8.2 6 8.2-6" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" />
  </svg>;

const IcArrow = () =>
  <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
    <path d="M6 12h12M13 6l6 6-6 6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
  </svg>;

const IcCheck = ({ className }) =>
  <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M3 12l4.5 4.5L14 8" />
    <path d="M10 12l4.5 4.5L21 8" opacity="0.55" />
  </svg>;


function IconLink({ href, children, label }) {
  return (
    <a className="icon-btn" href={href} target="_blank" rel="noreferrer" aria-label={label} title={label}>
      {children}
    </a>);
}

/* ---------- REVEAL ON SCROLL ---------- */
function useReveal(threshold = 0.15) {
  const ref = useRef(null);
  const [revealed, setRevealed] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    if (typeof IntersectionObserver === 'undefined') { setRevealed(true); return; }
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setRevealed(true); obs.disconnect(); }
    }, { threshold });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, [threshold]);
  return [ref, revealed];
}

/* ---------- LINK ROW (no nested anchors) ---------- */
function LinkRow({ thumbTag, thumbImg, thumbPos, title, titleClass, desc, tags, icons, href, external = true }) {
  const Wrap = ({ children }) =>
    href
      ? <a className="link-title-link" href={href} target={external ? '_blank' : undefined} rel={external ? 'noreferrer' : undefined}>{children}</a>
      : <span className="link-title-link">{children}</span>;

  return (
    <article className={`link-row ${href ? 'is-linked' : 'is-static'} ${thumbImg ? 'has-img' : ''}`}>
      <div className="link-thumb" aria-hidden="true">
        {thumbImg && <img className="link-thumb-img" src={thumbImg} alt="" loading="lazy" style={thumbPos ? { objectPosition: thumbPos } : undefined} />}
        {!thumbImg && <span className="link-thumb-tag">{thumbTag}</span>}
      </div>
      <div className="link-body">
        <h3 className={`link-title ${titleClass || ''}`}>
          <Wrap>{title}</Wrap>
        </h3>
        {desc && <p className="link-desc">{desc}</p>}
        {(tags || icons) &&
          <div className="link-meta">
            {tags}
            {icons && <div className="icon-row">{icons}</div>}
          </div>
        }
      </div>
      {href && <span className="link-arrow" aria-hidden="true"><IcArrow /></span>}
    </article>);
}

/* ---------- TRACKER ---------- */
const ACHIEVED = [
  'Live in Tokyo, Japan',
  'Live in Jakarta & Bali',
  'Live in Hong Kong & Singapore',
  'Meet the love of my life (other side of the world)',
  'Appear as model for a top beauty brand',
  'Make friends online → meet IRL → grow together',
  'Record a viral TikTok / Reel',
  'Reach 260 km/h in a car',
  'See Bad Bunny, Karol G live',
  'See Cristiano Ronaldo playing',
  'Walk alone in a foreign city with music',
  'Finding your true purpose and passion'];

const PENDING = [
  'Open an offline space',
  'Make a cameo in a movie',
  'Appear as model in a billboard campaign',
  'Learn diving',
  'Go on Umrah & Hajj',
  'Start a scholarship program',
  'Go on Safari',
  'See Gorillas in the wild',
  'See Kanye live',
  'Record a viral YouTube video'];

function TrackerItem({ text, done }) {
  return (
    <li className={`tr-item ${done ? 'done' : 'pending'}`}>
      <span className="tr-shovel-icon" aria-hidden="true" />
      <span className="tr-text">{text}</span>
    </li>);
}

function Tracker() {
  const [ref, revealed] = useReveal();
  return (
    <section ref={ref} className={`tracker reveal ${revealed ? 'is-revealed' : ''}`} aria-labelledby="tracker-title">
      <div className="sect-eyebrow">Goal Digger Tracker</div>
      <h2 id="tracker-title" className="tracker-title">What we've <em>dug</em> for.</h2>
      <p className="tracker-sub">
        Some of these took a decade. Some a few weeks. Some are pending. That's the point.
      </p>

      <div className="tr-columns">
        <ul className="tr-list">
          {ACHIEVED.map((t, i) => <TrackerItem key={i} text={t} done={true} />)}
        </ul>
        <ul className="tr-list">
          {PENDING.map((t, i) => <TrackerItem key={i} text={t} done={false} />)}
        </ul>
      </div>
    </section>);
}

/* ---------- ABOUT ---------- */
function AboutImage() {
  return (
    <div className="about-image" role="img" aria-label="Wiraj Seraj and Amirah Zerlett">
      <img
        className="about-image-photo"
        src="assets/thepeople-wiraj-amirah.jpg"
        alt="Wiraj Seraj and Amirah Zerlett"
        loading="lazy" />

      {/* Fallback typographic monogram — visible until image loads or if it 404s */}
      <span className="ai-fallback" aria-hidden="true">
        <span className="ai-w">W</span>
        <span className="ai-amp">&amp;</span>
        <span className="ai-a">A</span>
        <span className="ai-grain"></span>
      </span>
    </div>
  );
}

function About() {
  const [ref, revealed] = useReveal();
  // Render names with first letter as gold script flourish
  const goldFirst = (name) => {
    const first = name.charAt(0);
    const rest = name.slice(1);
    return <><span className="gold-letter">{first}</span><span className="rest">{rest}</span></>;
  };
  return (
    <section ref={ref} className={`about reveal ${revealed ? 'is-revealed' : ''}`} aria-labelledby="about-title">
      <div className="sect-eyebrow">The people</div>
      <h2 id="about-title" className="about-title">
        Wiraj Seraj <em>&amp;</em> Amirah Zerlett.
      </h2>

      <AboutImage />

      <div className="about-lede-stack">
        <p className="about-lede">
          Two people who didn't fit in. An immigrant who'd lost everything multiple times.
          A bullied Jakarta girl told she wasn't enough.
        </p>
        <p className="about-lede about-lede--secondary">
          We run on a single belief: when you help someone climb a mountain, you reach the top
          yourself. That's why Misi Lab exists. Not to build empires for ourselves, but to lift
          the people we work with and rise with them. A word that means "mission" in Dutch,
          English, and Bahasa. We cook up brands, ideas, communities, dreams.
        </p>
        <p className="about-lede about-lede--secondary">
          We reveal the patterns others miss, bringing both local Indonesian insights and global
          perspectives to content. This is the story of Wiraj Seraj and Amirah Zerlett. She knows
          Jakarta's heartbeat. He's seen how the world works.
        </p>
      </div>

      <div className="bios">
        <div className="bio">
          <div className="bio-name">{goldFirst('Amirah')} Zerlett</div>
          <div className="bio-role">Co-founder · Jakarta</div>
          <p className="bio-body">
            Grew up in Jakarta without privilege. Raised by her mother without her father. The
            only daughter. She remembers saving money just to buy bread. She remembers school
            hallways filled with whispers, her curly hair mocked, her skin doubted, her
            identity questioned.
          </p>
        </div>

        <div className="bio">
          <div className="bio-name">{goldFirst('Wiraj')} Seraj</div>
          <div className="bio-role">Co-founder · Amsterdam</div>
          <p className="bio-body">
            Born in Afghanistan. His parents fled war, leaving everything behind to give their
            children a chance at a better life. He went from basic jobs like washing dishes to
            working at top law firms in the Netherlands. Has worked and lived in Tokyo, Hong
            Kong, Singapore, US, to help brands grow and expand.
          </p>
        </div>
      </div>
    </section>);
}

/* ---------- WORDMARK (Misi Lab logo, dark/light auto-swap) ---------- */
function Wordmark({ size = 'sm' }) {
  return (
    <a href="#" className={`wordmark wordmark--${size}`} aria-label="Misi Lab">
      <img
        className="wordmark-img wordmark-img--light"
        src="assets/misilab-logo-light.svg"
        alt="Misi Lab" />

      <img
        className="wordmark-img wordmark-img--dark"
        src="assets/misilab-logo-dark.svg"
        alt="" aria-hidden="true" />

    </a>);
}

/* ---------- TWEAKS PANEL ---------- */
function MisilabTweaks({ tweaks, setTweak }) {
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Mood">
        <TweakRadio
          label="Theme"
          value={tweaks.theme}
          options={[
            { value: 'system', label: 'System' },
            { value: 'light', label: 'Light' },
            { value: 'dark', label: 'Dark' }]}
          onChange={(v) => setTweak('theme', v)} />

        <TweakRadio
          label="Misilab Blue accent"
          value={tweaks.accent}
          options={[
            { value: 'off', label: 'Off (gold)' },
            { value: 'subtle', label: 'Subtle' },
            { value: 'present', label: 'Present' }]}
          onChange={(v) => setTweak('accent', v)} />
      </TweakSection>
      <TweakSection title="Hero">
        <TweakRadio
          label="Stat treatment"
          value={tweaks.hero}
          options={[
            { value: 'editorial', label: 'Editorial (Garamond)' },
            { value: 'quiet', label: 'Quiet (sans)' }]}
          onChange={(v) => setTweak('hero', v)} />
      </TweakSection>
      <TweakSection title="Time strip">
        <TweakRadio
          label="Motion"
          value={tweaks.ticker}
          options={[
            { value: 'marquee', label: 'Marquee' },
            { value: 'static', label: 'Static' },
            { value: 'cycle', label: 'Fade cycle' }]}
          onChange={(v) => setTweak('ticker', v)} />
      </TweakSection>
    </TweaksPanel>);
}

/* ---------- ROOT ---------- */
function readUrlOverrides() {
  try {
    const p = new URLSearchParams(window.location.search);
    const out = {};
    ['theme', 'hero', 'accent', 'ticker', 'tracker'].forEach((k) => {
      const v = p.get(k); if (v) out[k] = v;
    });
    return out;
  } catch (e) { return {}; }
}

function App() {
  const overrides = readUrlOverrides();
  const [tweaks, setTweaks] = useTweaks({ ...DEFAULTS, ...overrides });
  const setTweak = (k, v) => setTweaks({ ...tweaks, [k]: v });

  useEffect(() => {
    const root = document.documentElement;
    if (tweaks.theme === 'system') root.removeAttribute('data-theme');
    else root.setAttribute('data-theme', tweaks.theme);
    root.setAttribute('data-hero', tweaks.hero);
    root.setAttribute('data-accent', tweaks.accent);
    root.setAttribute('data-ticker', tweaks.ticker);
    root.setAttribute('data-tracker', tweaks.tracker);
  }, [tweaks]);

  return (
    <>
      <Ticker />
      <div className="page">
        <header className="top-mark">
          <Wordmark />
        </header>

        {/* HERO — subheader only, two fixed lines */}
        <section className="hero" aria-labelledby="hero-tagline">
          <p id="hero-tagline" className="hero-quote">
            <span className="hq-line">We build, grow, invest, and advise brands</span>
            <span className="hq-line">on international expansions and story-driven content.</span>
          </p>
        </section>

        {/* LINK LIST — order: @wirilett, FROMFLOE, Clean Water, Goal Diggers, Misi Lab, Playbooks */}
        <div className="link-list">
          <LinkRow
            thumbTag="@wirilett"
            thumbImg="assets/wirilett.jpg"
            title="@wirilett"
            desc="A husband-and-wife creator whose work doesn't just go viral, it reshapes how a new generation thinks."
            href="https://wirilett.com"
            icons={<>
              <IconLink href="https://wirilett.com" label="Website"><IcGlobe /></IconLink>
              <IconLink href="https://www.instagram.com/wirilett" label="Instagram"><IcInstagram /></IconLink>
              <IconLink href="https://www.tiktok.com/@wirilett" label="TikTok"><IcTikTok /></IconLink>
              <IconLink href="https://www.youtube.com/@wirilett" label="YouTube"><IcYouTube /></IconLink>
            </>} />

          <LinkRow
            thumbTag="FROMFLOE"
            thumbImg="assets/sections/fromfloe.jpg"
            title="FROMFLOE"
            titleClass="sans"
            desc="The only water filter worth having. For glowing, healthy skin and hair."
            href="https://fromfloe.com"
            icons={<>
              <IconLink href="https://fromfloe.com" label="Website"><IcGlobe /></IconLink>
              <IconLink href="https://www.instagram.com/fromfloe" label="Instagram"><IcInstagram /></IconLink>
              <IconLink href="https://www.tiktok.com/@fromfloe" label="TikTok"><IcTikTok /></IconLink>
              <span className="tag-chip tag-chip--inline">Ships Globally</span>
            </>} />

          <LinkRow
            thumbTag="Water"
            thumbImg="assets/sections/clean-water.jpg"
            title="Clean Water Project"
            desc="Funding clean water initiatives in Indonesia. 3% of every FROMFLOE purchase contributes."
            icons={<IconLink href="mailto:fromfloe@misilab.com" label="Email"><IcMail /></IconLink>} />

          <LinkRow
            thumbTag="Diggers"
            thumbImg="assets/sections/goal-diggers.jpg"
            thumbPos="center 75%"
            title={<>Goal <span className="script">Diggers</span></>}
            desc="A female-only community for high-performing Indonesian women, the ones reshaping how a generation thinks, works, and spends."
            tags={<span className="tag-chip coming-soon"><span className="dot" />Coming soon</span>} />

          <LinkRow
            thumbTag="Misi Lab"
            thumbImg="assets/sections/misilab.jpg"
            title="Misi Lab"
            desc="We help you stand out. A lab cooking up missions. Brands. Ideas. Content. Communities. Dreams."
            icons={<IconLink href="mailto:wirilett@misilab.com" label="Email"><IcMail /></IconLink>} />

          <LinkRow
            thumbTag="Playbooks"
            thumbImg="assets/sections/playbooks.jpg"
            title="Playbooks"
            desc="What we've learned, written down. Exclusively shared with you."
            tags={<span className="tag-chip coming-soon"><span className="dot" />Coming soon</span>} />
        </div>

        <About />
        <Tracker />

        <footer>
          <Wordmark size="md" />
          <div className="foot-icons">
            <IconLink href="mailto:wirilett@misilab.com" label="Email"><IcMail /></IconLink>
          </div>
          <div className="foot-cred">
            <span>© {new Date().getFullYear()} Misi Lab Indonesia</span>
          </div>
        </footer>
      </div>

      <MisilabTweaks tweaks={tweaks} setTweak={setTweak} />
    </>);
}

window.MisilabApp = App;
