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

// ============================================================
// TWEAKS — defaults persisted in the EDITMODE block in HTML
// ============================================================

const DEFAULTS = (typeof window !== 'undefined' && window.__TWEAK_DEFAULTS) || {
  palette: 'paper',
  serif: 'newsreader',
  density: 'airy',
  hero_variant: 'sentence',
};

// ============================================================
// REVEAL — quiet fade-up on scroll (the "breathing" motion)
// ============================================================

function Reveal({ children, delay = 0, as: Tag = 'div', className = '', style }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    // Already in (or above) the viewport on mount — show immediately.
    const rect = el.getBoundingClientRect();
    const vh = window.innerHeight || document.documentElement.clientHeight;
    if (rect.top < vh - 20) { setShown(true); return; }
    if (typeof IntersectionObserver === 'undefined') { setShown(true); return; }
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setShown(true); obs.disconnect(); } });
    }, { threshold: 0, rootMargin: '0px 0px -10% 0px' });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return (
    <Tag
      ref={ref}
      className={className}
      style={{
        ...style,
        opacity: shown ? 1 : 0,
        transform: shown ? 'translateY(0)' : 'translateY(14px)',
        transition: `opacity 900ms cubic-bezier(.2,.6,.2,1) ${delay}ms, transform 900ms cubic-bezier(.2,.6,.2,1) ${delay}ms`,
      }}
    >
      {children}
    </Tag>
  );
}

// ============================================================
// SMALL UI ATOMS
// ============================================================

function Eyebrow({ children, num }) {
  return (
    <div className="eyebrow">
      {num && <span className="eyebrow-num">{num}</span>}
      <span>{children}</span>
    </div>
  );
}

function Rule() { return <div className="rule" />; }

function ArrowLink({ href, children, external = false }) {
  return (
    <a href={href} className="arrow-link" target={external ? '_blank' : undefined} rel={external ? 'noopener noreferrer' : undefined}>
      <span>{children}</span>
      <svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true">
        <path d="M2 10 L10 2 M4 2 L10 2 L10 8" stroke="currentColor" strokeWidth="1.2" fill="none" />
      </svg>
    </a>
  );
}

// ============================================================
// HEADER
// ============================================================

function Header() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <header className={`site-header ${scrolled ? 'is-scrolled' : ''}`}>
      <div className="header-inner">
        <a href="#top" className="lockup">
          <span className="mark" aria-hidden="true">
            <svg viewBox="0 0 24 24" width="20" height="20">
              <circle cx="12" cy="12" r="10.5" fill="none" stroke="currentColor" strokeWidth="1" />
              <path d="M7 14.5 Q12 8 17 14.5" fill="none" stroke="currentColor" strokeWidth="1" />
            </svg>
          </span>
          <span className="lockup-text">
            <span className="lockup-name">Ounadjela Advisory</span>
            <span className="lockup-domain">remiounadjela.com</span>
          </span>
        </a>
        <nav className="site-nav">
          <a href="#stanford">Stanford</a>
          <a href="#advisory">Advisory</a>
          <a href="#background">Background</a>
          <a href="#contact" className="nav-contact">Contact</a>
        </nav>
      </div>
    </header>
  );
}

// ============================================================
// HERO
// ============================================================

function Hero({ variant }) {
  return (
    <section className="hero" id="top">
      <div className="hero-inner">
        <Reveal delay={40}>
          <div className="hero-meta">
            <span>Mountain View, California</span>
            <span className="dot" />
            <span>Founded September 2025</span>
          </div>
        </Reveal>

        {variant === 'name-first' ? (
          <Reveal delay={120}>
            <h1 className="display">
              Remi Ounadjela.
            </h1>
            <p className="hero-sentence">
              I architect AI strategy and adoption. I lead the engagement, design the system,
              communicate to executives, and partner with implementation specialists for delivery.
            </p>
          </Reveal>
        ) : variant === 'letter' ? (
          <Reveal delay={120}>
            <h1 className="display display-letter">
              I'm Remi. I help leadership teams turn AI ambition into something
              they can actually decide on, build, and govern.
            </h1>
            <p className="hero-sentence">
              Eight years inside AI-first big tech. Now an independent advisor and Stanford lecturer.
            </p>
          </Reveal>
        ) : (
          <Reveal delay={120}>
            <h1 className="display">
              AI strategy and adoption,<br />
              for the people who have to decide.
            </h1>
            <p className="hero-sentence">
              I'm Remi Ounadjela. I lead the engagement, design the system, brief the executives,
              and bring in implementation specialists for the build.
            </p>
          </Reveal>
        )}

        <Reveal delay={260}>
          <div className="hero-badges">
            <a href="#stanford" className="badge">
              <span className="badge-label">Teaching</span>
              <span className="badge-value">Stanford Continuing Studies — TECH 75</span>
              <span className="badge-when">July 2026</span>
            </a>
            <a href="#advisory" className="badge badge-secondary">
              <span className="badge-label">Available for</span>
              <span className="badge-value">Advisory and fractional AI leadership</span>
            </a>
          </div>
        </Reveal>
      </div>
      <div className="hero-edge" aria-hidden="true" />
    </section>
  );
}

// ============================================================
// STANFORD
// ============================================================

function Stanford() {
  const facts = [
    ['Course', 'AI and Accountability'],
    ['Code', 'TECH 75'],
    ['Term', 'Summer 2026'],
    ['Schedule', 'Thursdays, Jul 2 \u2013 Jul 30'],
    ['Time', '6:00 \u2013 7:30 pm PT'],
    ['Format', 'Online, recorded'],
    ['Capped at', '45 students'],
    ['Tuition', '$355'],
    ['Registration', 'Opens May 18, 2026'],
  ];
  return (
    <section id="stanford" className="section section-stanford">
      <div className="section-inner">
        <Reveal>
          <Eyebrow num="01">Teaching</Eyebrow>
        </Reveal>

        <div className="stanford-grid">
          <div className="stanford-lead">
            <Reveal delay={40}>
              <h2 className="h2">
                Stanford Continuing Studies asked me to design and teach a course on
                how to evaluate AI before betting on it.
              </h2>
            </Reveal>
            <Reveal delay={120}>
              <p className="lede">
                Five weeks online in July 2026. Capped at 45 industry practitioners.
                We work through real deployments where AI succeeded and where it failed,
                alongside the governance frameworks (EU AI Act, sector-specific regulation,
                internal accountability structures) that increasingly shape what's possible.
              </p>
            </Reveal>
            <Reveal delay={200}>
              <p className="lede lede-quiet">
                Students leave with a working framework for evaluating any AI system
                they're asked to adopt, build, or sign off on.
              </p>
            </Reveal>
            <Reveal delay={280}>
              <div className="stanford-ctas">
                <a
                  href="https://continuingstudies.stanford.edu/courses/professional-and-personal-development/ai-and-accountability-how-to-evaluate-and-use-artificial-intelligence/20254_TECH-75"
                  target="_blank" rel="noopener noreferrer"
                  className="btn btn-primary"
                >
                  Register at Stanford
                  <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true">
                    <path d="M2 12 L12 2 M5 2 L12 2 L12 9" stroke="currentColor" strokeWidth="1.4" fill="none" />
                  </svg>
                </a>
                <span className="btn-meta">Registration opens May 18, 2026 at 8:30 am PT</span>
              </div>
            </Reveal>
          </div>

          <Reveal delay={160} className="stanford-card">
            <div className="card card-fact">
              <div className="card-head">
                <span className="card-tag">Course details</span>
                <span className="card-tag-right">Stanford Continuing Studies</span>
              </div>
              <dl className="fact-list">
                {facts.map(([k, v], i) => (
                  <div className="fact-row" key={i}>
                    <dt>{k}</dt>
                    <dd>{v}</dd>
                  </div>
                ))}
              </dl>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

// ============================================================
// ADVISORY (Services)
// ============================================================

function Advisory() {
  return (
    <section id="advisory" className="section">
      <div className="section-inner">
        <Reveal>
          <Eyebrow num="02">Working together</Eyebrow>
        </Reveal>
        <Reveal delay={60}>
          <h2 className="h2">
            Three ways to work with me.
          </h2>
        </Reveal>

        <div className="services">
          <Reveal delay={80} as="article" className="service">
            <div className="service-num">i.</div>
            <h3 className="service-title">Advisory and fractional AI leadership</h3>
            <p className="service-body">
              For leadership teams that need senior AI judgment without hiring a full-time
              executive yet. Engagements range from a focused diagnostic, a few weeks ending
              in a roadmap and a clear set of build / buy / skip decisions, to longer fractional
              embedments of two or three days a week leading the AI program internally.
            </p>
            <ul className="service-tags">
              <li>Mid-market and enterprise leadership teams</li>
              <li>PE operating partners on portco AI value creation</li>
              <li>Founders looking for a senior technical advisor</li>
            </ul>
          </Reveal>

          <Reveal delay={140} as="article" className="service">
            <div className="service-num">ii.</div>
            <h3 className="service-title">Speaking, keynotes, and workshops</h3>
            <p className="service-body">
              Conference keynotes, executive offsites, board-level workshops, and AI literacy
              sessions for leadership teams. The talks I give well are about evaluating AI
              investments, what AI-first organizations actually look like inside, AI in regulated
              industries, and accountability and governance.
            </p>
            <ul className="service-tags">
              <li>Conference and industry keynotes</li>
              <li>Executive offsites and board workshops</li>
              <li>Bilingual: English and French</li>
            </ul>
          </Reveal>

          <Reveal delay={200} as="article" className="service">
            <div className="service-num">iii.</div>
            <h3 className="service-title">Stanford TECH 75</h3>
            <p className="service-body">
              A five-week public course at Stanford Continuing Studies on evaluating and
              governing AI systems. Open to anyone; registration is through Stanford.
            </p>
            <div className="service-link">
              <ArrowLink href="#stanford">See course details</ArrowLink>
            </div>
          </Reveal>
        </div>

        <Reveal delay={260}>
          <div className="working-with">
            <div className="working-rule" />
            <p className="working-text">
              I work best with leadership teams that have genuine ambition for AI, an honest
              read on where they are today, and the willingness to make decisions when the
              diagnostic comes back. I don't take engagements that are looking for cover for
              a decision that's already been made.
            </p>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

// ============================================================
// BACKGROUND — narrative + case "tiles" (future-proofed for real cases)
// ============================================================

function Background() {
  return (
    <section id="background" className="section section-bg">
      <div className="section-inner">
        <Reveal>
          <Eyebrow num="03">Background</Eyebrow>
        </Reveal>
        <Reveal delay={60}>
          <h2 className="h2">
            Eight years inside AI-first big tech, building functions and shipping systems.
          </h2>
        </Reveal>

        <div className="bg-grid">
          <div className="bg-prose">
            <Reveal delay={80}>
              <p className="lede">
                Inside TikTok I built the EMEA Trust &amp; Safety data science function from
                zero, founded a 600-person internal training program, and currently lead the
                standardization of AI workflows across a 27-person regional DS organization.
              </p>
            </Reveal>
            <Reveal delay={140}>
              <p className="lede">
                I've briefed regulators in the UK, Ireland, France, and Canada on AI
                governance and transparency. The EU regulator described the work as
                <em> industry leading.</em>
              </p>
            </Reveal>
            <Reveal delay={200}>
              <p className="lede">
                Outside TikTok I've designed AI architectures for early-stage companies,
                including the technical roadmap that anchored a seed fundraise.
              </p>
            </Reveal>
          </div>

          <Reveal delay={120} className="bg-stats">
            <Stat n="27" label="Data scientists in the regional org I'm standardizing" />
            <Stat n="17" label="Markets running production LLM applications I shipped with my team" />
            <Stat n="50K+" label="Videos per week through the NLP pipeline behind transparency reporting" />
            <Stat n="5.8M" label={<>Videos swept in a single crisis response, <span className="stat-sub">98.4% accuracy</span></>} />
            <Stat n="600" label="Staff trained through the Data Science Academy I founded at TikTok" />
            <Stat n="16K" label="Followers on LinkedIn writing about AI in industry" />
          </Reveal>
        </div>

        <div className="cases">
          <Reveal delay={60}>
            <div className="cases-head">
              <h3 className="h3">Selected work</h3>
            </div>
          </Reveal>

          <div className="case-grid">
            <Reveal delay={80} as="article" className="case">
              <div className="case-meta">
                <span>2020 — 2024</span>
                <span className="case-status">Built</span>
              </div>
              <h4 className="case-title">TikTok Senior Data Science Manager</h4>
              <p className="case-body">
                Founded the EMEA Trust &amp; Safety data science function as the first hire
                and built it into a multi-site team across Dublin and San Jose. Shipped NLP
                and child-safety models into production across Europe and Latin America.
              </p>
              <span className="case-role">Role: founding lead</span>
            </Reveal>

            <Reveal delay={140} as="article" className="case">
              <div className="case-meta">
                <span>2025</span>
                <span className="case-status">Shipped</span>
              </div>
              <h4 className="case-title">TikTok AI Strategy &amp; Adoption Lead</h4>
              <p className="case-body">
                Authored TikTok's multi-year AI-First strategy and 12-month agentic data
                science adoption roadmap. Consolidated 11 fragmented LLM workstreams across
                AMS, EMEA, and APAC into one convergent architecture; shipped a retrieval-
                augmented escalation triage agent and an LLM evaluation framework now used
                in production across 17 markets.
              </p>
              <span className="case-role">Role: strategy &amp; adoption lead</span>
            </Reveal>

            <Reveal delay={200} as="article" className="case">
              <div className="case-meta">
                <span>2026</span>
                <span className="case-status">Shipped</span>
              </div>
              <h4 className="case-title">Trade finance compliance startup</h4>
              <p className="case-body">
                Full technical architecture and 12-week engineering roadmap for an early-
                stage trade finance compliance company. The document was the centerpiece of
                their seed fundraise.
              </p>
              <span className="case-role">Role: technical advisor</span>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

function Stat({ n, label }) {
  return (
    <div className="stat">
      <div className="stat-n">{n}</div>
      <div className="stat-label">{label}</div>
    </div>
  );
}

// ============================================================
// ABOUT — short, with a portrait slot
// ============================================================

function About() {
  return (
    <section id="about" className="section section-about">
      <div className="section-inner">
        <Reveal>
          <Eyebrow num="04">About</Eyebrow>
        </Reveal>

        <div className="about-grid">
          <Reveal delay={60} className="about-portrait-wrap">
            <div className="portrait-frame">
              <img src="assets/remi.png" alt="Remi Ounadjela" className="portrait-img" />
            </div>
            <div className="portrait-caption">Mountain View, 2026</div>
          </Reveal>

          <div className="about-text">
            <Reveal delay={80}>
              <p className="about-lede">
                I spent eight years inside AI-first big tech, Amazon, Google, and most
                recently TikTok, and now do that work for organizations that need it from
                the outside.
              </p>
            </Reveal>
            <Reveal delay={140}>
              <p className="about-body">
                I'm not a research-grade ML practitioner. I'm not a senior production
                engineer. I'm the person you bring in when your AI work needs strategy,
                structure, executive alignment, and a credible bridge between the people
                building it and the people deciding about it.
              </p>
            </Reveal>
            <Reveal delay={200}>
              <p className="about-body">
                Available globally. Comfortable across US and European time zones. Working
                language English; French native.
              </p>
            </Reveal>

            <Reveal delay={260}>
              <div className="about-facts">
                <div><span>Lives</span><span>Mountain View, California</span></div>
                <div><span>From</span><span>Paris, France</span></div>
                <div><span>Languages</span><span>English, French</span></div>
                <div><span>Writes at</span><span><a href="https://remiounadjela.substack.com" target="_blank" rel="noopener noreferrer">remiounadjela.substack.com</a></span></div>
              </div>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============================================================
// CONTACT
// ============================================================

function Contact() {
  const [copied, setCopied] = useState(false);
  const formRef = useRef(null);

  const onCompose = (e) => {
    e.preventDefault();
    const form = formRef.current;
    const topic = form.topic.value;
    const message = form.message.value.trim();
    const subjectMap = {
      advisory: 'Advisory inquiry',
      speaking: 'Speaking inquiry',
      course:   'Stanford TECH 75 question',
      other:    'Inquiry via remiounadjela.com',
    };
    const subject = encodeURIComponent(subjectMap[topic] || subjectMap.other);
    const body = encodeURIComponent(message);
    window.location.href = `mailto:remi@remiounadjela.com?subject=${subject}&body=${body}`;
  };

  const onCopy = async () => {
    try {
      await navigator.clipboard.writeText('remi@remiounadjela.com');
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    } catch (_) { /* ignore */ }
  };

  return (
    <section id="contact" className="section section-contact">
      <div className="section-inner">
        <Reveal>
          <Eyebrow num="05">Get in touch</Eyebrow>
        </Reveal>

        <div className="contact-grid">
          <div className="contact-lead">
            <Reveal delay={40}>
              <h2 className="h2">
                The right next step is a conversation.
              </h2>
            </Reveal>
            <Reveal delay={120}>
              <p className="lede">
                Tell me what you're working on and what you're trying to decide. I read
                every email. If we're a fit I'll suggest a call; if we're not, I'll usually
                point you to someone who is.
              </p>
            </Reveal>

            <Reveal delay={180}>
              <ul className="contact-channels">
                <li>
                  <span>Email</span>
                  <a href="mailto:remi@remiounadjela.com">remi@remiounadjela.com</a>
                </li>
                <li>
                  <span>LinkedIn</span>
                  <a href="https://www.linkedin.com/in/remi-ounadjela" target="_blank" rel="noopener noreferrer">in/remi-ounadjela</a>
                </li>
                <li>
                  <span>Writing</span>
                  <a href="https://remiounadjela.substack.com" target="_blank" rel="noopener noreferrer">remiounadjela.substack.com</a>
                </li>
              </ul>
            </Reveal>
          </div>

          <Reveal delay={120} className="contact-form-wrap">
            <form className="contact-form" ref={formRef} onSubmit={onCompose}>
              <label className="field">
                <span className="field-label">Reason</span>
                <select name="topic" defaultValue="advisory">
                  <option value="advisory">Advisory inquiry</option>
                  <option value="speaking">Speaking inquiry</option>
                  <option value="course">Stanford TECH 75 question</option>
                  <option value="other">Something else</option>
                </select>
              </label>
              <label className="field">
                <span className="field-label">Message</span>
                <textarea name="message" rows="6" required placeholder="What you're working on, what you're trying to decide, and any timing."></textarea>
              </label>
              <button type="submit" className="btn btn-primary btn-full">
                Open email
                <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true">
                  <path d="M2 7 H12 M8 3 L12 7 L8 11" stroke="currentColor" strokeWidth="1.4" fill="none" />
                </svg>
              </button>
              <p className="form-foot">
                This opens your mail client with the message pre-filled. No mail client?
                <button type="button" className="link-btn" onClick={onCopy}>
                  {copied ? 'Copied ✓' : 'Copy address'}
                </button>
                and write directly.
              </p>
            </form>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

// ============================================================
// FOOTER
// ============================================================

function Footer() {
  return (
    <footer className="site-footer">
      <div className="footer-inner">
        <div className="footer-lockup">
          <div className="footer-name">Ounadjela Advisory</div>
          <div className="footer-domain">remiounadjela.com</div>
        </div>
        <div className="footer-cols">
          <div>
            <div className="footer-h">Site</div>
            <a href="#stanford">Stanford</a>
            <a href="#advisory">Advisory</a>
            <a href="#background">Background</a>
            <a href="#about">About</a>
            <a href="#contact">Contact</a>
          </div>
          <div>
            <div className="footer-h">Elsewhere</div>
            <a href="https://www.linkedin.com/in/remi-ounadjela" target="_blank" rel="noopener noreferrer">LinkedIn</a>
            <a href="https://remiounadjela.substack.com" target="_blank" rel="noopener noreferrer">Substack</a>
            <a href="mailto:remi@remiounadjela.com">Email</a>
          </div>
          <div>
            <div className="footer-h">Practice</div>
            <span>Mountain View, CA</span>
            <span>Founded 2025</span>
            <span>Available globally</span>
          </div>
        </div>
      </div>
      <div className="footer-baseline">
        <span>© {new Date().getFullYear()} Ounadjela Advisory</span>
        <span>Last updated May 2026</span>
      </div>
    </footer>
  );
}

// ============================================================
// TWEAKS PANEL
// ============================================================

function Tweaks() {
  const { TweaksPanel, TweakSection, TweakColor, TweakRadio, useTweaks } = window;
  const [t, setTweak] = useTweaks(DEFAULTS);

  // Apply palette / serif / density to <html> as data-attrs
  useEffect(() => {
    const r = document.documentElement;
    r.setAttribute('data-palette', t.palette);
    r.setAttribute('data-serif', t.serif);
    r.setAttribute('data-density', t.density);
    r.setAttribute('data-hero', t.hero_variant);
  }, [t.palette, t.serif, t.density, t.hero_variant]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Palette">
        <TweakColor
          label="Background"
          value={t.palette}
          onChange={(v) => setTweak('palette', v)}
          options={[
            { value: 'paper', color: '#f3efe6' },
            { value: 'cream', color: '#ece4d2' },
            { value: 'bone',  color: '#f7f5f0' },
            { value: 'ink',   color: '#141414' },
          ]}
        />
      </TweakSection>
      <TweakSection title="Typography">
        <TweakRadio
          label="Display serif"
          value={t.serif}
          onChange={(v) => setTweak('serif', v)}
          options={[
            { value: 'newsreader', label: 'Newsreader' },
            { value: 'instrument', label: 'Instrument' },
            { value: 'dm',         label: 'DM Serif' },
          ]}
        />
      </TweakSection>
      <TweakSection title="Layout">
        <TweakRadio
          label="Density"
          value={t.density}
          onChange={(v) => setTweak('density', v)}
          options={[
            { value: 'airy',    label: 'Airy' },
            { value: 'compact', label: 'Compact' },
          ]}
        />
        <TweakRadio
          label="Hero"
          value={t.hero_variant}
          onChange={(v) => setTweak('hero_variant', v)}
          options={[
            { value: 'sentence',   label: 'Sentence' },
            { value: 'name-first', label: 'Name first' },
            { value: 'letter',     label: 'Letter' },
          ]}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

// ============================================================
// APP
// ============================================================

function App() {
  // Read live tweak state for hero variant. We mirror html data-attr → state.
  const [heroVariant, setHeroVariant] = useState(() =>
    document.documentElement.getAttribute('data-hero') || DEFAULTS.hero_variant
  );
  useEffect(() => {
    const obs = new MutationObserver(() => {
      setHeroVariant(document.documentElement.getAttribute('data-hero') || DEFAULTS.hero_variant);
    });
    obs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-hero'] });
    return () => obs.disconnect();
  }, []);

  return (
    <>
      <Header />
      <main>
        <Hero variant={heroVariant} />
        <Stanford />
        <Advisory />
        <Background />
        <About />
        <Contact />
      </main>
      <Footer />
      <Tweaks />
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
