function Ph({ label, className = '' }) {
  return <div className={'ph ' + className}><span>{label}</span></div>;
}

function Avatar() {
  const ref = React.useRef();
  const [hi, setHi] = React.useState(false);
  React.useEffect(() => {
    const mv = e => {
      const el = ref.current; if (!el) return;
      const r = el.getBoundingClientRect();
      const dx = (e.clientX - (r.left + r.width / 2)) / innerWidth, dy = (e.clientY - (r.top + r.height * .4)) / innerHeight;
      el.style.setProperty('--lx', clamp(dx * 2, -1, 1).toFixed(3));
      el.style.setProperty('--ly', clamp(dy * 2, -1, 1).toFixed(3));
    };
    window.addEventListener('pointermove', mv); return () => window.removeEventListener('pointermove', mv);
  }, []);
  const wave = () => { setHi(true); clearTimeout(ref.t); ref.t = setTimeout(() => setHi(false), 1800); };
  return (
    <div ref={ref} className={'av' + (hi ? ' hi' : '')} onClick={wave} title="Say hi">
      <div className="av-grid"></div>
      <div className="av-glow"></div>
      <div className="av-fig">
        <div className="av-body"><i className="av-zip"></i></div>
        <div className="av-neck"></div>
        <div className="av-head">
          <div className="av-hair"></div>
          <div className="av-face">
            <div className="av-eyes"><i></i><i></i></div>
            <div className="av-mouth"></div>
          </div>
          <div className="av-phones"><i></i><i></i></div>
        </div>
        <div className="av-laptop"><i></i></div>
      </div>
      <div className="av-bubble">merhaba!</div>
    </div>
  );
}

function AboutApp({ os }) {
  return (
    <div className="about">
      <aside className="ab-side">
        <Avatar />
        <dl className="ab-meta">
          <div><dt>Based in</dt><dd>{CV.based}</dd></div>
          <div><dt>From</dt><dd>{CV.from}</dd></div>
          <div><dt>Studying</dt><dd>Computer Science, TSI</dd></div>
        </dl>
      </aside>
      <div className="ab-main">
        <div className="eyebrow rise" style={{ '--d': 0 }}>{CV.role} · ex-cybersecurity</div>
        <h1 className="ab-name rise" style={{ '--d': 1 }}>{CV.first}<br />{CV.last}</h1>
        <p className="lede rise" style={{ '--d': 2 }}>I’m Ata Alp — a software developer from Istanbul, now living in Riga, where I study Computer Science at the Transport and Telecommunication Institute (TSI). I like building things end to end: system architecture, backend services, data pipelines and the mobile interface people actually touch.</p>
        <p className="rise" style={{ '--d': 3 }}>My main product is <a onClick={() => os.open('projects', { sel: 'vizeradar' })}>VizeRadar</a>, live on the App Store — a platform that monitors visa appointment systems in real time and alerts Turkish users the moment a slot opens. I designed and run the whole thing, from scraping and scheduling to notifications and production maintenance.</p>
        <p className="rise" style={{ '--d': 3 }}>Before that I spent two years as a cybersecurity specialist at PixelPlus in Istanbul — managing IT infrastructure and networks and helping implement ISO 27001. It still shapes how I build: monitored, reliable, secure by default. Lately I’m deep into AI — exploring how LLMs and automation can make products smarter and workflows faster.</p>
        <div className="ab-stack rise" style={{ '--d': 4 }}>
          <h4>What I work with</h4>
          <dl>
            <div><dt>Languages</dt><dd>JavaScript (ES6+) · TypeScript · Python · Swift · C++ · SQL</dd></div>
            <div><dt>Frontend & mobile</dt><dd>React · React Native · Context API · Redux</dd></div>
            <div><dt>Backend</dt><dd>Node.js · Express.js · REST APIs · Auth · Webhooks · Cron & background jobs</dd></div>
            <div><dt>Data</dt><dd>PostgreSQL · MySQL · SQLite · NoSQL · Schema design · Query optimization</dd></div>
            <div><dt>Automation</dt><dd>Web scraping · Selenium · Pipelines · Rate limiting · Bot-based monitoring</dd></div>
            <div><dt>Network & security</dt><dd>TCP/IP · DNS · HTTP/HTTPS · ISO 27001 · Infrastructure</dd></div>
            <div><dt>Interests</dt><dd>AI & LLMs · Automation · Product building</dd></div>
          </dl>
        </div>
        <div className="ab-grid rise" style={{ '--d': 4 }}>
          <section>
            <h4>Languages</h4>
            {CV.languages.map((l, i) => (
              <div className="lang" key={l.name}>
                <span>{l.name}</span><em>{l.level}</em>
                <div className="lbar"><i style={{ '--w': l.v / 6, animationDelay: D(500 + i * 90) + 'ms' }}></i></div>
              </div>
            ))}
          </section>
          <section>
            <h4>Education</h4>
            {CV.education.map(e => (
              <div className="edu" key={e.school}>
                <b>{e.field}</b><span>{e.school}</span><em>{e.dates} · {e.place}</em>
              </div>
            ))}
          </section>
        </div>
        <div className="acts rise" style={{ '--d': 5 }}>
          <button className="btn pri" onClick={() => os.open('projects')}>See projects</button>
          <a className="btn" href="portfolio/resume.pdf" download="Ata-Alp-Yildirim-CV.pdf">Download CV</a>
          <button className="btn ghost" onClick={() => os.open('contact')}>Get in touch</button>
        </div>
      </div>
    </div>
  );
}

function ProjectsApp({ os, args }) {
  const [sel, setSel] = React.useState(args?.sel || CV.projects[0].id);
  React.useEffect(() => { if (args?.sel) setSel(args.sel); }, [args]);
  const p = CV.projects.find(x => x.id === sel);
  return (
    <div className="prj">
      <aside className="prj-side">
        <div className="side-h">Projects <em>{CV.projects.length}</em></div>
        {CV.projects.map(x => (
          <button key={x.id} className={'prj-item' + (x.id === sel ? ' sel' : '')} onClick={() => setSel(x.id)}>
            <b>{x.name}</b><span>{x.tag}</span>
            <em><i className={'pulse' + (x.live ? ' live' : '')}></i>{x.status}</em>
          </button>
        ))}
      </aside>
      <article className="prj-detail" key={sel}>
        <Ph label={p.name.toLowerCase() + ' — app screenshots'} className="prj-hero rise" />
        <div className="prj-head rise" style={{ '--d': 1 }}>
          <h2>{p.name}</h2>
          <div className="prj-links">{p.links.map(l => <a key={l.href} className="btn sm" href={l.href} target="_blank" rel="noopener">{l.label} ↗</a>)}</div>
        </div>
        <dl className="prj-meta rise" style={{ '--d': 2 }}>
          <div><dt>Type</dt><dd>{p.kind}</dd></div>
          <div><dt>Role</dt><dd>{p.role}</dd></div>
          <div><dt>Timeline</dt><dd>{p.dates}</dd></div>
          <div><dt>Platform</dt><dd>{p.platform}</dd></div>
          <div><dt>Status</dt><dd>{p.status}</dd></div>
        </dl>
        <p className="lede rise" style={{ '--d': 3 }}>{p.summary}</p>
        <p className="rise" style={{ '--d': 4 }}>{p.body}</p>
        <div className="chips rise" style={{ '--d': 5 }}>{p.owns.map(o => <span className="chip" key={o}>{o}</span>)}</div>
      </article>
    </div>
  );
}

function ExperienceApp() {
  return (
    <div className="xp">
      <div className="eyebrow">Work experience</div>
      <div className="tl">
        {CV.experience.map((x, i) => (
          <section className="tl-item rise" key={x.co} style={{ '--d': i * 2 + 1 }}>
            <div className="tl-dot"><i className={x.now ? 'pulse live' : ''}></i></div>
            <div className="tl-date">{x.dates}</div>
            <h3>{x.role}</h3>
            <div className="tl-co">{x.co} · {x.place}</div>
            <ul>{x.points.map(pt => <li key={pt}>{pt}</li>)}</ul>
          </section>
        ))}
      </div>
      <div className="eyebrow" style={{ marginTop: 28 }}>Education</div>
      <div className="xp-edu">
        {CV.education.map((e, i) => (
          <a className="xp-card rise" key={e.school} href={e.href} target="_blank" rel="noopener" style={{ '--d': 5 + i }}>
            <em>{e.dates}</em><b>{e.field}</b><span>{e.school}</span><span className="dim">{e.place} · {e.level}</span>
          </a>
        ))}
      </div>
    </div>
  );
}

function SkillsApp() {
  const [hl, setHl] = React.useState(null);
  return (
    <div className="sk">
      <div className="sk-head">
        <div className="eyebrow">Stack</div>
        <div className="sk-filter">
          <button className={!hl ? 'on' : ''} onClick={() => setHl(null)}>All</button>
          {CV.skills.map(g => <button key={g.k} className={hl === g.k ? 'on' : ''} onClick={() => setHl(g.k)}>{g.k}</button>)}
        </div>
      </div>
      <div className="sk-grid">
        {CV.skills.map((g, gi) => (
          <section key={g.k} className={'sk-card rise' + (hl && hl !== g.k ? ' fade' : '') + (hl === g.k ? ' hot' : '')} style={{ '--d': gi }}>
            <div className="sk-k"><span>{String(gi + 1).padStart(2, '0')}</span>{g.k}</div>
            <div className="chips">{g.items.map((s, si) => <span className="chip pop" key={s} style={{ animationDelay: D(250 + gi * 70 + si * 30) + 'ms' }}>{s}</span>)}</div>
          </section>
        ))}
      </div>
    </div>
  );
}

function ResumeApp() {
  return (
    <div className="rs">
      <div className="rs-bar">
        <div className="rs-file"><AppIcon id="resume" size={22} /><b>resume-europass.pdf</b><em>2 pages</em></div>
        <div className="rs-acts">
          <a className="btn sm" href="portfolio/resume.pdf" target="_blank" rel="noopener">Open ↗</a>
          <a className="btn sm pri" href="portfolio/resume.pdf" download="Ata-Alp-Yildirim-CV.pdf">Download</a>
        </div>
      </div>
      <object className="rs-doc" data="portfolio/resume.pdf#view=FitH" type="application/pdf">
        <div className="rs-fb">
          <AppIcon id="resume" size={64} />
          <p>Preview isn’t available in this browser.</p>
          <a className="btn pri" href="portfolio/resume.pdf" download="Ata-Alp-Yildirim-CV.pdf">Download CV</a>
        </div>
      </object>
    </div>
  );
}

function ContactApp() {
  const [f, setF] = React.useState({ from: '', subj: '', msg: '' });
  const [sent, setSent] = React.useState(false);
  const send = e => {
    e.preventDefault();
    const body = encodeURIComponent(f.msg + (f.from ? `\n\n— ${f.from}` : ''));
    window.location.href = `mailto:${CV.email}?subject=${encodeURIComponent(f.subj || 'Hello Ata')}&body=${body}`;
    setSent(true);
  };
  const links = [
    { k: 'Email', v: CV.email, href: 'mailto:' + CV.email },
    CV.github && { k: 'GitHub', v: CV.github.replace(/^https?:\/\//, ''), href: CV.github },
    CV.linkedin && { k: 'LinkedIn', v: CV.linkedin.replace(/^https?:\/\//, ''), href: CV.linkedin },
    { k: 'VizeRadar', v: 'vizeradar.app', href: 'https://www.vizeradar.app/' }
  ].filter(Boolean);
  if (sent) return (
    <div className="ct-sent">
      <div className="ct-check"><i></i></div>
      <h3>Your mail app is open</h3>
      <p>Hit send there and I’ll get back to you.</p>
      <button className="btn" onClick={() => { setSent(false); setF({ from: '', subj: '', msg: '' }); }}>New message</button>
    </div>
  );
  return (
    <form className="ct" onSubmit={send}>
      <div className="ct-row"><label>To</label><span className="ct-to">{CV.name} &lt;{CV.email}&gt;</span></div>
      <div className="ct-row"><label>From</label><input value={f.from} onChange={e => setF({ ...f, from: e.target.value })} placeholder="your@email.com" /></div>
      <div className="ct-row"><label>Subject</label><input value={f.subj} onChange={e => setF({ ...f, subj: e.target.value })} placeholder="Project, role, or just hello" /></div>
      <textarea value={f.msg} onChange={e => setF({ ...f, msg: e.target.value })} placeholder="Write a message…" required></textarea>
      <div className="ct-foot">
        <div className="ct-links">{links.map(l => <a key={l.k} href={l.href} target="_blank" rel="noopener"><em>{l.k}</em>{l.v}</a>)}</div>
        <button className="btn pri" type="submit">Send ↵</button>
      </div>
    </form>
  );
}

const TERM_APPS = ['about', 'projects', 'experience', 'skills', 'resume', 'contact'];
function TerminalApp({ os }) {
  const [lines, setLines] = React.useState([{ c: 'dim', v: 'ata.os terminal — type `help` to get started' }]);
  const [val, setVal] = React.useState(''), [hist, setHist] = React.useState([]), [hi, setHi] = React.useState(-1);
  const box = React.useRef(), inp = React.useRef();
  React.useEffect(() => { box.current.scrollTop = box.current.scrollHeight; }, [lines]);
  React.useEffect(() => { setTimeout(() => inp.current && inp.current.focus(), 300); }, []);
  const out = arr => arr.map(v => typeof v === 'string' ? { v } : v);
  const run = raw => {
    const cmd = raw.trim(); const [c, ...a] = cmd.split(/\s+/); const arg = a.join(' ');
    let o = [];
    switch ((c || '').toLowerCase()) {
      case '': break;
      case 'help': o = ['whoami      who is this', 'ls          list files', 'projects    what I’m building', 'experience  where I’ve worked', 'skills      the stack', 'education   where I study', 'languages   what I speak', 'contact     how to reach me', 'open <app>  open a window', 'date        time in Riga', 'clear       clear screen', { c: 'acc', v: 'sudo hire-ata' }]; break;
      case 'whoami': o = [CV.name + ' — software developer, ex-cybersecurity.', 'Based in ' + CV.based + ', from ' + CV.from + '.']; break;
      case 'ls': o = [{ c: 'acc', v: 'about  projects/  experience  skills  resume.pdf  contact' }]; break;
      case 'projects': o = CV.projects.flatMap(p => [{ c: 'acc', v: p.name + '  ·  ' + p.dates }, '  ' + p.status + ' — ' + p.tag]); break;
      case 'experience': o = CV.experience.map(x => x.dates.padEnd(22) + x.role + ' @ ' + x.co); break;
      case 'education': o = CV.education.map(e => e.dates.padEnd(22) + e.field + ' — ' + e.school); break;
      case 'skills': o = CV.skills.flatMap(g => [{ c: 'acc', v: g.k }, '  ' + g.items.join(', ')]); break;
      case 'languages': o = CV.languages.map(l => l.name.padEnd(10) + '█'.repeat(l.v) + '░'.repeat(6 - l.v) + '  ' + l.level); break;
      case 'contact': case 'email': o = ['email   ' + CV.email]; break;
      case 'date': o = [fmt(new Date(), { dateStyle: 'full', timeStyle: 'short' }) + ' (Riga)']; break;
      case 'cat': o = arg === 'resume.pdf' ? ['binary file — try `open resume`'] : ['cat: ' + (arg || '?') + ': no such file']; break;
      case 'open': {
        const t = arg.replace(/\.pdf$|\/$/, '');
        if (TERM_APPS.includes(t)) { o = ['opening ' + t + '…']; setTimeout(() => os.open(t), D(250)); }
        else o = ['open: unknown app — try one of: ' + TERM_APPS.join(', ')];
        break;
      }
      case 'clear': setLines([]); return;
      case 'sudo':
        if (/hire/.test(arg)) { o = ['[sudo] password for recruiter: ********', { c: 'acc', v: 'access granted. opening contact…' }]; setTimeout(() => os.open('contact'), D(900)); }
        else o = ['nice try.'];
        break;
      case 'exit': os.close('terminal'); return;
      default: o = ['command not found: ' + c + ' — type `help`'];
    }
    setLines(l => [...l, { c: 'cmd', v: cmd }, ...out(o)]);
  };
  const key = e => {
    if (e.key === 'Enter') { run(val); if (val.trim()) setHist(h => [val, ...h]); setVal(''); setHi(-1); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); const n = Math.min(hi + 1, hist.length - 1); if (n >= 0) { setHi(n); setVal(hist[n]); } }
    else if (e.key === 'ArrowDown') { e.preventDefault(); const n = hi - 1; setHi(n); setVal(n >= 0 ? hist[n] : ''); }
    else if (e.key === 'Tab') {
      e.preventDefault();
      const all = ['help', 'whoami', 'ls', 'projects', 'experience', 'education', 'skills', 'languages', 'contact', 'date', 'clear', 'sudo hire-ata', ...TERM_APPS.map(a => 'open ' + a)];
      const m = all.find(x => x.startsWith(val) && val); if (m) setVal(m);
    }
  };
  return (
    <div className="term" ref={box} onClick={() => inp.current.focus()}>
      {lines.map((l, i) => l.c === 'cmd'
        ? <div key={i} className="tl-cmd"><b>ata@riga</b> <i>~</i> $ {l.v}</div>
        : <div key={i} className={'tl-out ' + (l.c || '')}>{l.v}</div>)}
      <div className="tl-cmd live"><b>ata@riga</b> <i>~</i> $
        <input ref={inp} value={val} onChange={e => setVal(e.target.value)} onKeyDown={key} spellCheck="false" autoCapitalize="off" autoComplete="off" />
      </div>
    </div>
  );
}

Object.assign(window, { AboutApp, ProjectsApp, ExperienceApp, SkillsApp, ResumeApp, ContactApp, TerminalApp });
