// editorial.jsx — Monospace / terminal-coded contrasting direction
const { useState: uS, useEffect: uE, useRef: uR } = React;

function useReveal2(opts = {}) {
  const ref = uR(null);
  const [shown, setShown] = uS(false);
  uE(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => { if (e.isIntersecting) setShown(true); }),
      { threshold: opts.threshold ?? 0.18, rootMargin: '0px 0px -8% 0px' }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return [ref, shown];
}

function useTyped(text, speed = 28, start = true) {
  const [out, setOut] = uS('');
  uE(() => {
    if (!start) return;
    setOut('');
    let i = 0;
    const id = setInterval(() => {
      i++;
      setOut(text.slice(0, i));
      if (i >= text.length) clearInterval(id);
    }, speed);
    return () => clearInterval(id);
  }, [text, start, speed]);
  return out;
}

function EdHero({ data, accent }) {
  const [started, setStarted] = uS(false);
  uE(() => { const t = setTimeout(() => setStarted(true), 300); return () => clearTimeout(t); }, []);
  const line1 = useTyped("$ whoami", 40, started);
  const line2 = useTyped(data.name, 50, line1.length >= 8);
  const line3 = useTyped(data.longTagline, 22, line2.length >= data.name.length);

  return (
    <section className="ed-hero" data-screen-label="01 Hero">
      <div className="ed-hero-bg" aria-hidden="true">
        <div className="ed-hero-grid" />
        <div className="ed-hero-scan" />
        <div className="ed-hero-glow" style={{ background: `radial-gradient(closest-side, ${accent}, transparent 70%)` }} />
      </div>
      <div className="ed-hero-inner">
        <header className="ed-hero-head">
          <span className="ed-mono">~/portfolio</span>
          <span className="ed-mono">{data.location} · 2026</span>
        </header>
        <pre className="ed-hero-pre">
          <span className="ed-prompt" style={{ color: accent }}>{line1}<span className="ed-cursor">▍</span></span>{'\n'}
          <span className="ed-hero-name">{line2}</span>{line2 && '.'}{'\n'}
          <span className="ed-hero-tag">{line3}</span>
        </pre>
        <footer className="ed-hero-foot">
          <span className="ed-mono">[ scroll ↓ ]</span>
          <span className="ed-mono" style={{ color: accent }}>● {data.available}</span>
        </footer>
      </div>
    </section>
  );
}

function EdSection({ idx, label, title, children }) {
  const [ref, shown] = useReveal2();
  return (
    <section ref={ref} className={`ed-section ${shown ? 'is-shown' : ''}`} data-screen-label={`${String(idx).padStart(2, '0')} ${label}`}>
      <div className="ed-section-inner">
        <div className="ed-section-head">
          <span className="ed-mono ed-section-num">§ {String(idx).padStart(2, '0')}</span>
          <span className="ed-mono ed-section-label">{label}</span>
        </div>
        <h2 className="ed-h2">{title}</h2>
        <div className="ed-section-body">{children}</div>
      </div>
    </section>
  );
}

function EdAbout({ data }) {
  return (
    <EdSection idx={2} label="ABOUT" title="// about.md">
      <p className="ed-prose">{data.blurb}</p>
      <div className="ed-kv">
        <div className="ed-kv-row"><span className="ed-mono">role</span><span>{data.specialties.join(' / ')}</span></div>
        <div className="ed-kv-row"><span className="ed-mono">location</span><span>{data.location}</span></div>
        <div className="ed-kv-row"><span className="ed-mono">status</span><span>{data.available}</span></div>
      </div>
    </EdSection>
  );
}

function EdProjects({ data, accent }) {
  return (
    <EdSection idx={3} label="WORK" title="// selected projects">
      <div className="ed-projects">
        {data.projects.map((p, i) => (
          <article key={p.id} className="ed-project" style={{ '--i': i }}>
            <div className="ed-project-rail">
              <span className="ed-mono" style={{ color: accent }}>{String(i + 1).padStart(2, '0')}</span>
              <span className="ed-mono ed-project-year">{p.year}</span>
            </div>
            <div className="ed-project-main">
              <header>
                <h3 className="ed-project-name">{p.name}</h3>
                <span className="ed-mono ed-project-tag">{p.tag}</span>
              </header>
              <p className="ed-project-summary">{p.summary}</p>
              <ul className="ed-project-stack">
                {p.stack.map((s) => <li key={s} className="ed-mono">{s}</li>)}
              </ul>
            </div>
            <div className="ed-project-thumb" style={{ background: `linear-gradient(135deg, oklch(0.30 0.12 ${p.hue}), oklch(0.18 0.06 ${p.hue}))` }}>
              <span className="ed-mono">[ {p.id} ]</span>
            </div>
          </article>
        ))}
      </div>
    </EdSection>
  );
}

function EdExperience({ data, accent }) {
  return (
    <EdSection idx={4} label="HISTORY" title="// experience.log">
      <div className="ed-log">
        {data.experience.map((x, i) => (
          <div key={i} className="ed-log-row">
            <span className="ed-mono ed-log-period">{x.period}</span>
            <span className="ed-mono" style={{ color: accent }}>›</span>
            <div>
              <div className="ed-log-role">{x.role} <span className="ed-log-at">@ {x.company}</span></div>
              <div className="ed-log-note">{x.note}</div>
            </div>
          </div>
        ))}
      </div>
      <div className="ed-edu">
        {data.education.map((e, i) => (
          <div key={i} className="ed-log-row">
            <span className="ed-mono ed-log-period">{e.period}</span>
            <span className="ed-mono" style={{ color: accent }}>›</span>
            <div>
              <div className="ed-log-role">{e.degree} <span className="ed-log-at">@ {e.school}</span></div>
              <div className="ed-log-note">{e.note}</div>
            </div>
          </div>
        ))}
      </div>
    </EdSection>
  );
}

function EdSkills({ data, accent }) {
  return (
    <EdSection idx={5} label="STACK" title="// toolkit">
      <div className="ed-stack-grid">
        {Object.entries(data.skills).map(([cat, items]) => (
          <div key={cat} className="ed-stack-col">
            <div className="ed-mono ed-stack-cat" style={{ color: accent }}>{cat.toLowerCase()}/</div>
            <ul>
              {items.map((s) => <li key={s} className="ed-mono">— {s}</li>)}
            </ul>
          </div>
        ))}
      </div>
      <div className="ed-interests">
        <div className="ed-mono ed-stack-cat" style={{ color: accent }}>off-hours/</div>
        <ul>
          {data.interests.map((s) => <li key={s} className="ed-mono">— {s}</li>)}
        </ul>
      </div>
    </EdSection>
  );
}

function EdContactForm({ accent }) {
  const [form, setForm] = uS({ name: '', email: '', message: '' });
  const [status, setStatus] = uS('idle');
  const submit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.email || !form.message) return;
    setStatus('sending');
    try {
      const res = await fetch('https://formspree.io/f/xjglprpn', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify(form),
      });
      if (!res.ok) throw new Error('submit failed');
      setStatus('sent');
      setTimeout(() => { setStatus('idle'); setForm({ name: '', email: '', message: '' }); }, 2400);
    } catch {
      setStatus('error');
      setTimeout(() => setStatus('idle'), 3200);
    }
  };
  return (
    <form className="ed-form" onSubmit={submit}>
      <div className="ed-form-row">
        <label className="ed-form-field">
          <span className="ed-mono" style={{ color: accent }}>name =</span>
          <input value={form.name} onChange={(e) => setForm({...form, name: e.target.value})} placeholder='"Your name"' required />
        </label>
        <label className="ed-form-field">
          <span className="ed-mono" style={{ color: accent }}>email =</span>
          <input type="email" value={form.email} onChange={(e) => setForm({...form, email: e.target.value})} placeholder='"you@domain.com"' required />
        </label>
      </div>
      <label className="ed-form-field">
        <span className="ed-mono" style={{ color: accent }}>message =</span>
        <textarea rows={5} value={form.message} onChange={(e) => setForm({...form, message: e.target.value})} placeholder='"""..."""' required />
      </label>
      <button type="submit" className="ed-form-submit" disabled={status !== 'idle'}>
        <span className="ed-mono" style={{ color: accent }}>$ send</span>
        <span>
          {status === 'idle' && '→'}
          {status === 'sending' && '…'}
          {status === 'sent' && '✓ delivered'}
          {status === 'error' && '✗ failed'}
        </span>
      </button>
    </form>
  );
}

function EdContact({ data, accent }) {
  return (
    <EdSection idx={6} label="CONTACT" title="// say hello">
      <EdContactForm accent={accent} />
      <div className="ed-contact-grid" style={{ marginTop: 48 }}>
        <a className="ed-contact-card" href={`mailto:${data.links.email}`}>
          <span className="ed-mono ed-contact-key" style={{ color: accent }}>email →</span>
          <span className="ed-contact-val">{data.links.email}</span>
        </a>
        <a className="ed-contact-card" href={data.links.github} target="_blank" rel="noreferrer">
          <span className="ed-mono ed-contact-key" style={{ color: accent }}>github →</span>
          <span className="ed-contact-val">@sim-yujie</span>
        </a>
        <a className="ed-contact-card" href={data.links.linkedin} target="_blank" rel="noreferrer">
          <span className="ed-mono ed-contact-key" style={{ color: accent }}>linkedin →</span>
          <span className="ed-contact-val">/in/sim-yu-jie</span>
        </a>
        <button className="ed-contact-card" type="button" onClick={() => window.print()}>
          <span className="ed-mono ed-contact-key" style={{ color: accent }}>resume ↓</span>
          <span className="ed-contact-val">Download PDF</span>
        </button>
      </div>
      <footer className="ed-foot">
        <span className="ed-mono">© 2026 {data.name}</span>
        <span className="ed-mono">handcrafted · sg</span>
      </footer>
    </EdSection>
  );
}

window.Editorial = { EdHero, EdAbout, EdProjects, EdExperience, EdSkills, EdContact };
