// Direction A — Editorial. Warm cream/ink palette, Instrument Serif display,
// IBM Plex Sans body. Generous whitespace. Projects as long-form case-study
// blocks with sidebar metadata.

const DirectionA = ({ tweaks }) => {
  const [theme, setTheme] = React.useState('light');
  const [activeSection, setActiveSection] = React.useState('intro');
  const rootRef = React.useRef(null);

  React.useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const sections = root.querySelectorAll('[data-section]');
    const io = new IntersectionObserver(
      (entries) => {
        const visible = entries.filter((e) => e.isIntersecting).sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
        if (visible[0]) setActiveSection(visible[0].target.dataset.section);
      },
      { root, rootMargin: '-30% 0px -60% 0px', threshold: 0 }
    );
    sections.forEach((s) => io.observe(s));
    return () => io.disconnect();
  }, []);

  const accent = tweaks.accentA;
  const dense = tweaks.density === 'compact' ? 0.78 : tweaks.density === 'spacious' ? 1.15 : 1;
  const display = tweaks.typeA === 'serif'
    ? '"Instrument Serif", "Cormorant Garamond", Georgia, serif'
    : tweaks.typeA === 'transitional'
    ? '"Fraunces", "Cormorant Garamond", Georgia, serif'
    : '"Space Grotesk", "Helvetica Neue", Arial, sans-serif';

  const palette = theme === 'light'
    ? {
        bg: 'oklch(0.97 0.012 75)',
        bgAlt: 'oklch(0.94 0.014 75)',
        ink: 'oklch(0.18 0.01 60)',
        muted: 'oklch(0.42 0.01 60)',
        line: 'oklch(0.85 0.014 75)',
        card: 'oklch(0.99 0.008 75)',
      }
    : {
        bg: 'oklch(0.16 0.008 60)',
        bgAlt: 'oklch(0.19 0.01 60)',
        ink: 'oklch(0.94 0.01 75)',
        muted: 'oklch(0.68 0.01 75)',
        line: 'oklch(0.28 0.01 60)',
        card: 'oklch(0.19 0.01 60)',
      };

  const css = `
    .dir-a { --bg:${palette.bg}; --bg-alt:${palette.bgAlt}; --ink:${palette.ink}; --muted:${palette.muted}; --line:${palette.line}; --card:${palette.card}; --accent:${accent}; --d:${dense};
      background:var(--bg); color:var(--ink); font-family:'IBM Plex Sans', system-ui, sans-serif; font-feature-settings:'ss01','cv11';
      min-height:100%; transition:background .35s ease, color .35s ease; }
    .dir-a .display { font-family:${display}; font-weight:400; letter-spacing:-0.02em; }
    .dir-a .mono { font-family:'IBM Plex Mono', ui-monospace, monospace; }
    .dir-a a { color:inherit; text-decoration:none; }
    .dir-a .a-link { position:relative; transition:color .2s; }
    .dir-a .a-link::after { content:''; position:absolute; left:0; right:0; bottom:-2px; height:1px; background:currentColor; transform-origin:left; transform:scaleX(0); transition:transform .35s cubic-bezier(.2,.7,.3,1); }
    .dir-a .a-link:hover::after { transform:scaleX(1); }
    .dir-a .a-accent { color:var(--accent); }
    .dir-a .a-fade { opacity:0; transform:translateY(14px); transition:opacity .8s, transform .8s; }
    .dir-a .a-fade.in { opacity:1; transform:none; }
    .dir-a .a-card { background:var(--card); border:1px solid var(--line); border-radius:2px; }
    .dir-a .a-thumb { background:linear-gradient(135deg, var(--bg-alt) 0%, var(--card) 100%); border:1px solid var(--line); position:relative; overflow:hidden; }
    .dir-a .a-thumb::before { content:''; position:absolute; inset:0; background-image:repeating-linear-gradient(135deg, transparent 0 14px, var(--line) 14px 15px); opacity:.5; }
    .dir-a .a-chip { display:inline-block; padding:4px 10px; border:1px solid var(--line); border-radius:999px; font-size:11px; letter-spacing:.04em; color:var(--muted); }
    .dir-a .a-nav-link[data-current="true"] { color:var(--accent); }
    .dir-a .a-nav-link[data-current="true"]::before { content:'·'; margin-right:6px; }
    .dir-a .a-iconbtn { display:inline-flex; align-items:center; justify-content:center; width:34px; height:34px; border-radius:999px; border:1px solid var(--line); color:var(--ink); transition:background .2s, border-color .2s; background:transparent; cursor:pointer; }
    .dir-a .a-iconbtn:hover { background:var(--bg-alt); border-color:var(--accent); color:var(--accent); }
    .dir-a .a-section { padding:calc(120px * var(--d)) calc(96px * var(--d)); }
    .dir-a .a-rule { height:1px; background:var(--line); }
    .dir-a .a-num { font-family:'IBM Plex Mono',monospace; font-size:11px; letter-spacing:.18em; text-transform:uppercase; color:var(--muted); }
    .dir-a .a-h2 { font-size:48px; line-height:1.05; margin:0; }
    .dir-a .a-pjr { padding:calc(64px * var(--d)) 0; border-top:1px solid var(--line); }
    .dir-a .a-pjr:last-child { border-bottom:1px solid var(--line); }
    .dir-a .a-skill-pill { font-size:13px; color:var(--ink); padding:6px 0; border-bottom:1px solid var(--line); display:flex; justify-content:space-between; }
    .dir-a .a-skill-pill .mono { color:var(--muted); font-size:11px; }
    .dir-a .a-quote { font-style:italic; color:var(--muted); }
    .dir-a .a-italic { font-style:italic; }
    .dir-a .a-bigname { font-size:clamp(110px, 16vw, 220px); line-height:.92; }
  `;

  const [mounted, setMounted] = React.useState(false);
  React.useEffect(() => { const t = setTimeout(() => setMounted(true), 50); return () => clearTimeout(t); }, []);

  return (
    <div ref={rootRef} className="dir-a" data-theme={theme}
      style={{ height: '100%', overflowY: 'auto', overflowX: 'hidden', scrollBehavior: 'smooth' }}>
      <style>{css}</style>

      {/* Top nav */}
      <header style={{ position:'sticky', top:0, zIndex:20, background:'color-mix(in oklab, var(--bg) 88%, transparent)', backdropFilter:'blur(10px)', borderBottom:`1px solid ${palette.line}` }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'18px 48px' }}>
          <a href="#intro" className="mono" style={{ fontSize:12, letterSpacing:'.16em', textTransform:'uppercase' }}>Davin&nbsp;Seng <span style={{ color:palette.muted, marginLeft:8 }}>— Software Engineer</span></a>
          <nav style={{ display:'flex', gap:28, alignItems:'center' }}>
            {[
              { id:'about', label:'About' },
              { id:'work', label:'Selected Work' },
              { id:'experience', label:'Experience' },
              { id:'education', label:'Education' },
              { id:'skills', label:'Skills' },
              { id:'contact', label:'Contact' },
            ].map(l => (
              <a key={l.id} href={`#a-${l.id}`} className="a-nav-link a-link mono" data-current={activeSection===l.id}
                onClick={(e)=>{ e.preventDefault(); rootRef.current.querySelector(`[data-section="${l.id}"]`)?.scrollIntoView({ behavior:'smooth', block:'start' }); }}
                style={{ fontSize:12, letterSpacing:'.12em', textTransform:'uppercase' }}>{l.label}</a>
            ))}
            <button onClick={()=>setTheme(t => t==='light'?'dark':'light')} className="a-iconbtn" title={`Switch to ${theme==='light'?'dark':'light'} mode`}>
              <Icon name={theme==='light'?'moon':'sun'} size={15}/>
            </button>
          </nav>
        </div>
      </header>

      {/* Hero */}
      <section data-section="intro" className="a-section" style={{ paddingTop:`${80*dense}px`, paddingBottom:`${64*dense}px` }}>
        <div className={`a-fade ${mounted?'in':''}`} style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:24, alignItems:'baseline', marginBottom:48 }}>
          <span className="a-num">01 — Hello</span>
          <div className="a-rule"/>
        </div>
        <h1 className={`display a-bigname a-fade ${mounted?'in':''}`} style={{ margin:0, transitionDelay:'.1s' }}>
          Davin <span className="a-italic a-accent">Seng</span>
        </h1>
        <div style={{ display:'grid', gridTemplateColumns:'1.2fr 1fr', gap:80, marginTop:64 }}>
          <p className={`display a-fade ${mounted?'in':''}`} style={{ fontSize:36, lineHeight:1.25, margin:0, maxWidth:680, transitionDelay:'.2s' }}>
            A full-stack software engineer with a focus on back-end.
          </p>
          <div className={`a-fade ${mounted?'in':''}`} style={{ transitionDelay:'.3s' }}>
            <div className="mono" style={{ fontSize:11, letterSpacing:'.18em', textTransform:'uppercase', color:palette.muted, marginBottom:14 }}>Currently</div>
            <p style={{ margin:'0 0 18px', fontSize:15, lineHeight:1.65, color:palette.ink }}>Software engineer in {ME.location} — most recently at Lytx (SWE I → III), building data pipelines and .NET microservices. Open to new full-time backend roles.</p>
            <div style={{ display:'flex', gap:10, flexWrap:'wrap', marginTop:24 }}>
              <a className="a-link mono" href={`mailto:${ME.email}`} style={{ fontSize:12, letterSpacing:'.1em', textTransform:'uppercase', display:'inline-flex', alignItems:'center', gap:8, padding:'10px 18px', border:`1px solid ${palette.ink}`, background:palette.ink, color:palette.bg, borderRadius:999 }}>
                Get in touch <Icon name="arrow" size={13}/>
              </a>
              <a className="a-link mono" href="#a-work" onClick={(e)=>{e.preventDefault(); rootRef.current.querySelector('[data-section="work"]')?.scrollIntoView({behavior:'smooth'});}} style={{ fontSize:12, letterSpacing:'.1em', textTransform:'uppercase', display:'inline-flex', alignItems:'center', gap:8, padding:'10px 18px', border:`1px solid ${palette.line}`, borderRadius:999 }}>
                See work
              </a>
            </div>
          </div>
        </div>
      </section>

      {/* About */}
      <section data-section="about" className="a-section" style={{ background:palette.bgAlt }}>
        <div style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:24, alignItems:'baseline', marginBottom:64 }}>
          <span className="a-num">02 — About</span>
          <div className="a-rule"/>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'5fr 4fr', gap:96 }}>
          <div>
            {ME.longBio.split('\n\n').map((p, i) => (
              <p key={i} className="display" style={{ fontSize: i===0?30:24, lineHeight:1.4, margin:'0 0 28px', color: i===0?palette.ink:palette.muted }}>
                {i===0 ? <><span className="a-italic a-accent">Hi</span>{p.slice(2)}</> : p}
              </p>
            ))}
          </div>
          <div style={{ paddingTop:8 }}>
            <div className="a-thumb" style={{ aspectRatio:'4 / 5', marginBottom:32 }}>
              <div style={{ position:'absolute', inset:0, display:'flex', alignItems:'flex-end', padding:20 }}>
                <span className="mono" style={{ fontSize:10, letterSpacing:'.14em', textTransform:'uppercase', color:palette.muted, background:palette.bg, padding:'4px 8px' }}>portrait · 4:5</span>
              </div>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:20 }}>
              <div>
                <div className="mono" style={{ fontSize:10, letterSpacing:'.16em', textTransform:'uppercase', color:palette.muted, marginBottom:6 }}>Education</div>
                <div style={{ fontSize:14, lineHeight:1.5 }}>B.S. Electrical Engineering<br/><span style={{ color:palette.muted }}>UC San Diego · 2019</span></div>
              </div>
              <div>
                <div className="mono" style={{ fontSize:10, letterSpacing:'.16em', textTransform:'uppercase', color:palette.muted, marginBottom:6 }}>Location</div>
                <div style={{ fontSize:14, lineHeight:1.5 }}>San Diego, CA<br/><span style={{ color:palette.muted }}>PT (UTC−8)</span></div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Selected Work */}
      <section data-section="work" className="a-section">
        <div style={{ display:'grid', gridTemplateColumns:'auto 1fr auto', gap:24, alignItems:'baseline', marginBottom:64 }}>
          <span className="a-num">03 — Selected Work</span>
          <div className="a-rule"/>
          <span className="mono" style={{ fontSize:11, letterSpacing:'.16em', textTransform:'uppercase', color:palette.muted }}>{PROJECTS.length} projects</span>
        </div>
        <div>
          {PROJECTS.map((p, idx) => (
            <article key={p.id} className="a-pjr">
              <div style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:64 }}>
                <div className="mono" style={{ fontSize:13, color:palette.muted, paddingTop:14, minWidth:50 }}>0{idx+1}</div>
                <div style={{ display:'grid', gridTemplateColumns:'5fr 7fr', gap:48, alignItems:'start' }}>
                  <div>
                    <h3 className="display" style={{ fontSize:64, lineHeight:1, margin:'0 0 8px' }}>{p.name}</h3>
                    <div className="mono" style={{ fontSize:11, letterSpacing:'.14em', textTransform:'uppercase', color:palette.muted, marginBottom:24 }}>{p.year} · {p.platform}</div>
                    <p className="display a-italic" style={{ fontSize:22, lineHeight:1.35, margin:'0 0 18px', color:palette.ink }}>{p.tagline}</p>
                    <p style={{ fontSize:14, lineHeight:1.65, margin:'0 0 28px', color:palette.muted, maxWidth:420 }}>{p.description}</p>

                    <div style={{ display:'grid', gridTemplateColumns:'auto 1fr', columnGap:20, rowGap:10, marginBottom:24, alignItems:'baseline' }}>
                      <div className="mono" style={{ fontSize:10, letterSpacing:'.14em', textTransform:'uppercase', color:palette.muted }}>Role</div>
                      <div style={{ fontSize:13 }}>{p.role}</div>
                      <div className="mono" style={{ fontSize:10, letterSpacing:'.14em', textTransform:'uppercase', color:palette.muted }}>Stack</div>
                      <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>{p.stack.map(s => <span key={s} className="a-chip">{s}</span>)}</div>
                      <div className="mono" style={{ fontSize:10, letterSpacing:'.14em', textTransform:'uppercase', color:palette.muted }}>Status</div>
                      <div style={{ fontSize:13, color:palette.muted }}>{p.status}</div>
                    </div>

                    <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
                      {p.links.map(l => (
                        <a key={l.label} href={l.href} target="_blank" rel="noreferrer" className="a-link"
                          style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'12px 0', borderBottom:`1px solid ${palette.line}`, fontSize:14 }}>
                          <span>{l.label}</span>
                          <span style={{ color:palette.muted, display:'inline-flex', alignItems:'center', gap:8 }}>
                            <span className="mono" style={{ fontSize:11, letterSpacing:'.1em', textTransform:'uppercase' }}>{(()=>{ try { return new URL(l.href).hostname.replace('www.',''); } catch { return ''; } })()}</span>
                            <Icon name="external" size={14}/>
                          </span>
                        </a>
                      ))}
                    </div>
                  </div>

                  <div>
                    <div className="a-thumb" style={{ aspectRatio: ['Android','iOS','Mobile'].includes(p.platform) ? '4 / 5' : '16 / 10', position:'relative' }}>
                      <div style={{ position:'absolute', inset:0, background:`radial-gradient(circle at 30% 30%, color-mix(in oklab, ${p.accent} 35%, transparent), transparent 60%)` }}/>
                      <div style={{ position:'absolute', inset:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:16 }}>
                        <div style={{ width:64, height:64, borderRadius:p.platform==='Hardware'?6:16, background:p.accent, opacity:.9, display:'flex', alignItems:'center', justifyContent:'center', color:'#fff', fontSize:28, fontFamily:'"Instrument Serif",serif' }}>
                          {p.name[0]}
                        </div>
                        <span className="mono" style={{ fontSize:10, letterSpacing:'.18em', textTransform:'uppercase', color:palette.muted }}>{p.name} · cover</span>
                      </div>
                    </div>
                    <div className="mono" style={{ fontSize:10, letterSpacing:'.14em', textTransform:'uppercase', color:palette.muted, marginTop:14, display:'flex', justifyContent:'space-between' }}>
                      <span>fig {idx+1}.0 · {p.name}</span>
                      <span>{p.platform.toLowerCase()}</span>
                    </div>
                  </div>
                </div>
              </div>
            </article>
          ))}
        </div>
      </section>

      {/* Experience */}
      <section data-section="experience" className="a-section" style={{ background:palette.bgAlt }}>
        <div style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:24, alignItems:'baseline', marginBottom:64 }}>
          <span className="a-num">04 — Experience</span>
          <div className="a-rule"/>
        </div>
        <div>
          {EXPERIENCE.map((e, i) => (
            <div key={i} style={{ display:'grid', gridTemplateColumns:'180px 1fr auto', gap:48, padding:'28px 0', borderTop:`1px solid ${palette.line}`, alignItems:'baseline' }}>
              <div className="mono" style={{ fontSize:12, letterSpacing:'.08em', color:palette.muted }}>{e.period}</div>
              <div>
                <h4 className="display" style={{ fontSize:30, margin:'0 0 4px', lineHeight:1.1 }}>{e.role} <span className="a-italic a-accent">@ {e.company}</span></h4>
                <p style={{ margin:'0', fontSize:14, lineHeight:1.6, color:palette.muted, maxWidth:640 }}>{e.notes}</p>
                {e.placeholder && <span className="mono a-chip" style={{ marginTop:10, display:'inline-block', borderStyle:'dashed' }}>placeholder · edit me</span>}
              </div>
              <div className="mono" style={{ fontSize:11, letterSpacing:'.1em', textTransform:'uppercase', color:palette.muted }}>{e.location}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Education */}
      <section data-section="education" className="a-section">
        <div style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:24, alignItems:'baseline', marginBottom:64 }}>
          <span className="a-num">05 — Education</span>
          <div className="a-rule"/>
        </div>
        <div>
          {EDUCATION.map((e, i) => (
            <div key={i} style={{ display:'grid', gridTemplateColumns:'180px 1fr auto', gap:48, padding:'28px 0', borderTop:`1px solid ${palette.line}`, alignItems:'baseline' }}>
              <div className="mono" style={{ fontSize:12, letterSpacing:'.08em', color:palette.muted }}>{e.period}</div>
              <div>
                <h4 className="display" style={{ fontSize:30, margin:'0 0 4px', lineHeight:1.1 }}>{e.degree} <span className="a-italic a-accent">@ {e.school}</span></h4>
                <p style={{ margin:'0', fontSize:14, lineHeight:1.6, color:palette.muted, maxWidth:640 }}>{e.notes}</p>
              </div>
              <div className="mono" style={{ fontSize:11, letterSpacing:'.1em', textTransform:'uppercase', color:palette.muted }}>{e.location}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Skills */}
      <section data-section="skills" className="a-section" style={{ background:palette.bgAlt }}>
        <div style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:24, alignItems:'baseline', marginBottom:64 }}>
          <span className="a-num">06 — Skills & Tools</span>
          <div className="a-rule"/>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(5, 1fr)', gap:48 }}>
          {SKILLS.map(g => (
            <div key={g.group}>
              <h5 className="mono" style={{ fontSize:11, letterSpacing:'.18em', textTransform:'uppercase', color:palette.muted, margin:'0 0 14px' }}>{g.group}</h5>
              <div>
                {g.items.map((it, i) => (
                  <div key={it} className="a-skill-pill"><span>{it}</span><span className="mono">0{i+1}</span></div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Contact */}
      <section data-section="contact" className="a-section" style={{ background:palette.ink, color:palette.bg, paddingTop:`${140*dense}px`, paddingBottom:`${100*dense}px` }}>
        <div style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:24, alignItems:'baseline', marginBottom:64 }}>
          <span className="mono" style={{ fontSize:11, letterSpacing:'.18em', textTransform:'uppercase', color:'color-mix(in oklab, '+palette.bg+' 60%, transparent)' }}>07 — Say hi</span>
          <div style={{ height:1, background:'color-mix(in oklab, '+palette.bg+' 30%, transparent)' }}/>
        </div>
        <h2 className="display" style={{ fontSize:clamp_(96, 200), lineHeight:.95, margin:'0 0 56px', maxWidth:1100 }}>
          Let's <span className="a-italic" style={{ color:accent }}>build</span> something quietly remarkable.
        </h2>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:64 }}>
          <div>
            <a href={`mailto:${ME.email}`} className="display a-link" style={{ fontSize:42, color:palette.bg, display:'inline-flex', alignItems:'center', gap:18 }}>
              {ME.email} <Icon name="arrow" size={28}/>
            </a>
            <div style={{ marginTop:24, color:'color-mix(in oklab, '+palette.bg+' 65%, transparent)', fontSize:14, lineHeight:1.6, maxWidth:520 }}>
              Best for: backend engineering at scale, data pipelines, and full-stack systems work.
            </div>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:0, alignSelf:'start' }}>
            {[
              { icon:'github', label:'GitHub', value:ME.socials.github, href:`https://github.com/${ME.socials.github}` },
              { icon:'linkedin', label:'LinkedIn', value:ME.socials.linkedin, href:`https://linkedin.com/in/${ME.socials.linkedin}` },
              { icon:'twitter', label:'Twitter', value:'@'+ME.socials.twitter, href:`https://twitter.com/${ME.socials.twitter}` },
              { icon:'code', label:'CodePen', value:ME.socials.codepen, href:`https://codepen.io/${ME.socials.codepen}` },
            ].map(s => (
              <a key={s.label} href={s.href} target="_blank" rel="noreferrer" className="a-link"
                style={{ display:'flex', alignItems:'center', gap:14, padding:'18px 4px', borderTop:'1px solid color-mix(in oklab, '+palette.bg+' 20%, transparent)', fontSize:15 }}>
                <Icon name={s.icon} size={18}/>
                <span style={{ flex:1 }}>{s.label}</span>
                <span className="mono" style={{ fontSize:12, color:'color-mix(in oklab, '+palette.bg+' 60%, transparent)' }}>{s.value}</span>
              </a>
            ))}
          </div>
        </div>
        <div style={{ marginTop:120, paddingTop:32, borderTop:'1px solid color-mix(in oklab, '+palette.bg+' 20%, transparent)', display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
          <span className="mono" style={{ fontSize:11, letterSpacing:'.16em', textTransform:'uppercase', color:'color-mix(in oklab, '+palette.bg+' 55%, transparent)' }}>© {new Date().getFullYear()} Sovanarung "Davin" Seng</span>
          <span className="display a-italic" style={{ fontSize:18, color:'color-mix(in oklab, '+palette.bg+' 65%, transparent)' }}>handcrafted, sentence by sentence.</span>
        </div>
      </section>
    </div>
  );
};

function clamp_(min, max) { return `clamp(${min}px, ${(max/13).toFixed(1)}vw, ${max}px)`; }

window.DirectionA = DirectionA;
