/* ============ ATHARV.OS — Window Content Components ============ */

const ICO = window.ATHARV_ICONS;
const D = window.ATHARV_DATA;

const Ico = ({ name, size = 32, color }) => {
  const fn = ICO[name];
  if (!fn) return null;
  return <span className="ico" dangerouslySetInnerHTML={{ __html: fn(size, color) }} />;
};

/* ===== About ===== */
function AboutContent() {
  const [tab, setTab] = React.useState('general');
  return (
    <div style={{display:'flex', flexDirection:'column', flex:1, minHeight:0}}>
      <div className="about-tabs">
        {['general','contact','philosophy'].map(t =>
          <button key={t} className={`about-tab ${tab===t?'active':''}`} onClick={()=>setTab(t)}>
            {t==='general'?'General':t==='contact'?'Contact':'Philosophy'}
          </button>
        )}
      </div>
      <div className="about-pane">
        {tab==='general' && (
          <>
            <div className="row">
              <div className="photo"><img src="assets/profile.jpg" alt="Atharv Sharma" /></div>
              <div style={{flex:1}}>
                <h2>{D.identity.name}</h2>
                <div style={{fontSize:11, color:'#404040', marginBottom:4}}>aka <b>devarv</b></div>
                <p style={{marginTop:4, fontSize:11, lineHeight:1.5}}>{D.identity.role}</p>
                <div className="kv">
                  <span className="k">Education:</span><span>{D.education.school}</span>
                  <span className="k">Degree:</span><span>{D.education.degree}</span>
                  <span className="k">GPA:</span><span>{D.education.gpa}</span>
                  <span className="k">Graduation:</span><span>{D.education.grad}</span>
                  <span className="k">Location:</span><span>{D.identity.location}</span>
                </div>
              </div>
            </div>
            <hr style={{margin:'12px 0', border:'none', borderTop:'1px solid #fff', borderBottom:'1px solid #808080'}}/>
            <h3 style={{fontSize:12, fontWeight:700, marginBottom:4}}>Summary</h3>
            <p>{D.summary}</p>
            <h3 style={{fontSize:12, fontWeight:700, margin:'8px 0 4px'}}>Core Pillars</h3>
            <ul>{D.pillars.map((p,i)=><li key={i}>{p}</li>)}</ul>
          </>
        )}
        {tab==='contact' && (
          <>
            <h2>Contact</h2>
            <div className="kv" style={{marginTop:10}}>
              <span className="k">Email:</span><span><a href={`mailto:${D.identity.email}`}>{D.identity.email}</a></span>
              <span className="k">LinkedIn:</span><span><a href={D.identity.linkedin} target="_blank" rel="noreferrer">linkedin.com/in/atharv-sharma-devarv</a></span>
              <span className="k">GitHub:</span><span><a href={D.identity.github} target="_blank" rel="noreferrer">github.com/Atharv5873</a></span>
              <span className="k">Live:</span><span><a href={D.identity.royalbank} target="_blank" rel="noreferrer">Royal Bank Pacific</a> · <a href={D.identity.megointern} target="_blank" rel="noreferrer">Mego Agent Portal</a> · <a href={D.identity.copilot} target="_blank" rel="noreferrer">CI/CD Copilot</a></span>
            </div>
          </>
        )}
        {tab==='philosophy' && (
          <>
            <h2>Why ATHARV.OS</h2>
            <p>This portfolio is a statement: <b>I shipped real production systems, not slide decks.</b> Every project here runs in production or ran in a real lab. The interface is a tribute to Windows 95 — the OS I grew up troubleshooting on dusty hand-me-down PCs in the foothills of Manali.</p>
            <p>I believe in three things:</p>
            <ul>
              <li><b>Self-healing systems.</b> Pages should be a last resort.</li>
              <li><b>Zero-knowledge by default.</b> Trust the user; encrypt the rest.</li>
              <li><b>The mountain teaches latency.</b> Slow networks force good architecture.</li>
            </ul>
            <p style={{marginTop:8, fontStyle:'italic', color:'#404040'}}>"Good systems, like good music, work because of the silence between the notes."</p>
          </>
        )}
      </div>
    </div>
  );
}

/* ===== Project window ===== */
function ProjectContent({ proj }) {
  const [tab, setTab] = React.useState('overview');
  const tabs = [
    {id:'overview', label:'Overview'},
    ...(proj.story && proj.story.length ? [{id:'story', label:'Story'}] : []),
    ...(proj.screenshots && proj.screenshots.length ? [{id:'shots', label:'Screenshots'}] : []),
    {id:'highlights', label:'Highlights'},
    {id:'stack', label:'Stack'},
    {id:'links', label:'Links'},
  ];
  return (
    <div style={{display:'flex', flexDirection:'column', flex:1, minHeight:0, padding:6}}>
      <div className="proj-banner" style={{
        background: `linear-gradient(135deg, ${proj.themeColor} 0%, #000 130%)`,
      }}>
        <div className="pbtxt">
          <h2>{proj.name} <span style={{fontSize:11, opacity:0.7, fontWeight:400}}>{proj.version}</span></h2>
          <div className="tagline">{proj.tagline}</div>
        </div>
        <div className="pbicon" dangerouslySetInnerHTML={{__html: ICO[proj.iconKey] ? ICO[proj.iconKey](56, '#fff') : ''}}/>
        <div className="pbmetric">{proj.headlineMetric}</div>
      </div>
      <div className="tag-row">
        {proj.stack.slice(0,8).map((t,i) => <span className="tag" key={i}>{t}</span>)}
      </div>
      <div className="proj-tabs">
        {tabs.map(t =>
          <button key={t.id} className={`proj-tab ${tab===t.id?'active':''}`} onClick={()=>setTab(t.id)}>{t.label}</button>
        )}
      </div>
      <div className="proj-pane">
        {tab==='overview' && (
          <>
            <h3>Tagline</h3>
            <p>{proj.tagline}</p>
            <h3>Metadata</h3>
            <div className="meta">
              <span className="k">Duration:</span><span>{proj.duration}</span>
              <span className="k">Last worked:</span><span>{proj.lastWorked}</span>
              <span className="k">Headline metric:</span><span>{proj.headlineMetric}</span>
            </div>
          </>
        )}
        {tab==='story' && (
          <>
            {proj.story.map((s,i) => (
              <div key={i} style={{marginBottom:10}}>
                <h3>{s.h}</h3>
                <p>{s.p}</p>
              </div>
            ))}
          </>
        )}
        {tab==='shots' && (
          <>
            {proj.screenshots.map((s,i) => (
              <div key={i} style={{marginBottom:12}}>
                <a href={s.file} target="_blank" rel="noreferrer" title="Open full size">
                  <img src={s.file} alt={s.caption} loading="lazy" style={{
                    width:'100%', display:'block',
                    border:'2px solid', borderColor:'#404040 #FFFFFF #FFFFFF #404040',
                  }}/>
                </a>
                <div style={{fontSize:10, color:'#404040', marginTop:4, textAlign:'center'}}>{s.caption} — click to enlarge</div>
              </div>
            ))}
          </>
        )}
        {tab==='highlights' && (
          <>
            <h3>Key Highlights</h3>
            <ul>{proj.highlights.map((h,i)=><li key={i}>{h}</li>)}</ul>
          </>
        )}
        {tab==='stack' && (
          <>
            <h3>Tech Stack</h3>
            <div className="tag-row">
              {proj.stack.map((t,i) => <span className="tag" key={i}>{t}</span>)}
            </div>
          </>
        )}
        {tab==='links' && (
          <div className="links" style={{flexDirection:'column', gap:6}}>
            {proj.repo && <a className="btn" href={proj.repo} target="_blank" rel="noreferrer">📦 Repository</a>}
            {proj.live && <a className="btn" href={proj.live} target="_blank" rel="noreferrer">🌐 Live demo</a>}
          </div>
        )}
      </div>
    </div>
  );
}

/* ===== Experience ===== */
function ExperienceContent() {
  return (
    <div className="wbody white" style={{padding:14, lineHeight:1.5, fontSize:11}}>
      {D.experience.map((e,i) => (
        <div key={i} style={{marginBottom:18, paddingBottom:14, borderBottom:'1px dashed #ccc'}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', flexWrap:'wrap', gap:6}}>
            <h3 style={{fontSize:13, fontWeight:700}}>{e.role}</h3>
            <span style={{fontSize:10, color:'#404040', fontFamily:'Fixedsys, monospace'}}>{e.period}</span>
          </div>
          <div style={{fontSize:11, color:'#1f3a72', fontWeight:700, marginBottom:6}}>{e.company}{e.link && <> · <a href={e.link} target="_blank" rel="noreferrer">{e.link.replace(/https?:\/\//,'')}</a></>}</div>
          <ul style={{marginLeft:18}}>
            {e.bullets.map((b,j) => <li key={j} style={{marginBottom:3}}>{b}</li>)}
          </ul>
        </div>
      ))}
    </div>
  );
}

/* ===== Skills ===== */
function SkillsContent() {
  const [active, setActive] = React.useState(D.skillCategories[0].name);
  const cat = D.skillCategories.find(c => c.name === active);
  return (
    <div style={{display:'flex', flex:1, minHeight:0, padding:4, gap:4}}>
      <div className="sunken" style={{width:160, background:'#fff', overflow:'auto', padding:6}}>
        {D.skillCategories.map(c => (
          <div key={c.name}
            onClick={()=>setActive(c.name)}
            style={{
              padding:'4px 8px', cursor:'pointer', fontSize:11,
              background: active===c.name ? '#000080' : 'transparent',
              color: active===c.name ? '#fff' : '#000',
              marginBottom:1
            }}>{c.name}</div>
        ))}
      </div>
      <div className="sunken" style={{flex:1, background:'#fff', overflow:'auto'}}>
        <div style={{padding:'8px 14px', borderBottom:'1px solid #ccc', fontWeight:700, fontSize:12}}>{cat.name} — {cat.skills.length} items</div>
        <div className="skills-list">
          {cat.skills.map((s,i) => (
            <div className="skill-row" key={i}>
              <span>{s.n}</span>
              <div className="skill-bar"><div className="fill" style={{width: s.lvl + '%'}}/></div>
              <span style={{fontFamily:'Fixedsys, monospace', fontSize:10, textAlign:'right'}}>{s.lvl}%</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ===== Awards ===== */
function AwardsContent() {
  const [sel, setSel] = React.useState(null);
  if (sel !== null) {
    const a = D.awards[sel];
    return (
      <div className="wbody white" style={{padding:0}}>
        <div style={{padding:'4px 6px', display:'flex', gap:4, borderBottom:'1px solid #ccc'}}>
          <button className="btn" onClick={()=>setSel(null)}>← Back</button>
        </div>
        <div className="award-detail">
          <h3>{a.title}</h3>
          <div style={{fontSize:11, color:'#404040', marginBottom:12}}>{a.year}</div>
          {a.photo ? (
            <div className="photo-frame">
              <img src={a.photo} alt={a.title}/>
              <div className="cap">{a.caption}</div>
            </div>
          ) : (
            <div className="photo-frame" style={{padding:30, textAlign:'center'}}>
              <span dangerouslySetInnerHTML={{__html: ICO.cert(96)}}/>
              <div className="cap">{a.caption}</div>
            </div>
          )}
          <p style={{marginTop:8}}>{a.desc}</p>
        </div>
      </div>
    );
  }
  return (
    <div className="wbody white" style={{padding:0}}>
      <div className="awards-grid">
        {D.awards.map((a,i) => (
          <div className="award-card" key={i} onDoubleClick={()=>setSel(i)} onClick={()=>setSel(i)}>
            <div className="trophy" dangerouslySetInnerHTML={{__html: a.photo ? ICO.trophy(64) : ICO.cert(64)}}/>
            <div className="ttl">{a.title.split('—')[0].trim()}</div>
            <div className="yr">{a.year}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ===== Photos ===== */
// Map "assets/photos/Name.jpg" → optimized WebP in assets/photos/opt/ using a
// URL-safe slug (no spaces). Falls back to the original if the pattern misses.
function photoOpt(file, kind) {
  const m = /^assets\/photos\/(.+)\.(jpe?g|png)$/i.exec(file || '');
  if (!m) return file;
  const slug = m[1].toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
  return `assets/photos/opt/${slug}${kind === 'thumb' ? '.thumb' : ''}.webp`;
}

function PhotosContent() {
  const [sel, setSel] = React.useState(null);
  if (sel !== null) {
    const p = D.photos[sel];
    return (
      <div className="wbody white" style={{padding:0}}>
        <div style={{padding:'4px 6px', display:'flex', gap:4, borderBottom:'1px solid #ccc'}}>
          <button className="btn" onClick={()=>setSel(null)}>← Back</button>
          <button className="btn" disabled={sel===0} onClick={()=>setSel(s=>s-1)}>◀ Prev</button>
          <button className="btn" disabled={sel===D.photos.length-1} onClick={()=>setSel(s=>s+1)}>Next ▶</button>
          <span style={{flex:1}}/>
          <span style={{fontSize:11, padding:4}}>{sel+1} of {D.photos.length}</span>
        </div>
        <div className="photo-viewer">
          <div className="full">
            <div className="img" style={{height:380, backgroundImage:`url("${photoOpt(p.file,'full')}")`, backgroundSize:'contain', backgroundRepeat:'no-repeat', backgroundPosition:'center', backgroundColor:'#000'}}/>
          </div>
          <div className="meta">
            <h3>{p.caption}</h3>
            <p style={{fontStyle:'italic', color:'#404040', fontSize:11}}>{p.note}</p>
            <div className="exif">
              [EXIF]<br/>
              Camera: {p.exif.camera}<br/>
              Date: {p.exif.date}<br/>
              ISO: {p.exif.iso}<br/>
              {p.exif.f}<br/>
              {p.exif.shutter}<br/>
              Focal: {p.exif.focal}
              {p.exif.gps && <><br/>GPS: {p.exif.gps}</>}
            </div>
          </div>
        </div>
      </div>
    );
  }
  return (
    <div className="wbody white" style={{padding:0}}>
      <div className="photogrid">
        {D.photos.map((p,i) => (
          <div className="photo" key={i} onClick={()=>setSel(i)}>
            <div className="img" style={{backgroundImage:`url("${photoOpt(p.file,'thumb')}")`, backgroundSize:'cover', backgroundPosition:'center'}}/>
            <div className="cap">{p.caption}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ===== Notes ===== */
function NotesContent({ notepadText, setNotepadText }) {
  return (
    <div style={{display:'flex', flex:1, flexDirection:'column', minHeight:0}}>
      <textarea
        className="notepad-body"
        value={notepadText}
        onChange={e => setNotepadText(e.target.value)}
        spellCheck={false}
      />
    </div>
  );
}

/* ===== Network Neighborhood ===== */
function NetworkContent({ openExternal }) {
  const [gh, setGh] = React.useState(() => {
    try { return JSON.parse(sessionStorage.getItem('gh-stats')) || null; } catch (e) { return null; }
  });
  React.useEffect(() => {
    if (gh) return;
    fetch('https://api.github.com/users/Atharv5873')
      .then(r => r.ok ? r.json() : null)
      .then(d => {
        if (!d || typeof d.public_repos !== 'number') return;
        const stats = { repos: d.public_repos, followers: d.followers };
        setGh(stats);
        try { sessionStorage.setItem('gh-stats', JSON.stringify(stats)); } catch (e) {}
      })
      .catch(() => {}); // rate-limited or offline — just show nothing
  }, []);
  const items = [
    { name: 'GitHub', icon: 'github', url: D.identity.github },
    { name: 'LinkedIn', icon: 'linkedin', url: D.identity.linkedin },
    { name: 'Royal Bank Pacific', icon: 'globe', url: D.identity.royalbank },
    { name: 'Mego Agent Portal', icon: 'globe', url: D.identity.megointern },
    { name: 'CI/CD Copilot', icon: 'globe', url: D.identity.copilot },
    { name: 'SecurePass Vault', icon: 'globe', url: D.identity.securepass },
    { name: 'Email atharv@', icon: 'email', url: `mailto:${D.identity.email}` },
  ];
  return (
    <div className="wbody white" style={{padding:0, display:'flex', flexDirection:'column'}}>
      <div className="netgrid" style={{flex:1}}>
        {items.map((it,i) => (
          <div className="item" key={i} onDoubleClick={()=>window.open(it.url,'_blank')} onClick={()=>window.open(it.url,'_blank')}>
            <div className="ico" dangerouslySetInnerHTML={{__html: ICO[it.icon] ? ICO[it.icon](48) : ''}}/>
            <div className="lbl">{it.name}</div>
          </div>
        ))}
      </div>
      <div className="statusbar">
        <div className="scell flex">{items.length} network resource(s)</div>
        {gh && <div className="scell">GitHub: {gh.repos} public repos · {gh.followers} followers</div>}
      </div>
    </div>
  );
}

/* ===== Resume PDF ===== */
function ResumeContent() {
  const url = "assets/Resume.pdf";
  return (
    <div className="pdf-viewer">
      <div className="pdf-toolbar">
        <a className="btn" href={url} download="Atharv-Sharma-Resume.pdf" onClick={()=>window.va&&window.va('event',{name:'download_resume',data:{from:'viewer'}})}>💾 Download</a>
        <a className="btn" href={url} target="_blank" rel="noreferrer">⎘ Open in new tab</a>
        <span style={{flex:1}}/>
        <span style={{fontSize:11, alignSelf:'center', color:'#fff'}}>Resume.pdf — Atharv Sharma</span>
      </div>
      <div className="pdf-frame">
        <object data={url} type="application/pdf" width="100%" height="100%" style={{minHeight:600, background:'#fff'}}>
          <embed src={url} type="application/pdf" style={{width:'100%', height:'100%', minHeight:600}}/>
          <div style={{padding:24, background:'#fff', color:'#000', fontSize:12, lineHeight:1.6}}>
            <p>Your browser doesn't support inline PDFs.</p>
            <p style={{marginTop:8}}>
              <a className="btn" href={url} download="Atharv-Sharma-Resume.pdf">💾 Download Resume.pdf</a>
              {' '}
              <a className="btn" href={url} target="_blank" rel="noreferrer">⎘ Open in new tab</a>
            </p>
          </div>
        </object>
      </div>
    </div>
  );
}

/* ===== Run dialog ===== */
function RunDialog({ onRun, onClose }) {
  const [val, setVal] = React.useState('');
  const inp = React.useRef();
  React.useEffect(()=>{ inp.current?.focus(); }, []);
  return (
    <div className="run-dialog">
      <div style={{display:'flex', gap:10}}>
        <span style={{fontSize:32}}>🏃</span>
        <p style={{fontSize:11, lineHeight:1.4}}>
          Type the name of a program, folder, document, or Internet resource, and Atharv will open it for you.
        </p>
      </div>
      <div className="row">
        <span style={{fontSize:11, width:50}}>Open:</span>
        <input ref={inp} className="w95-input" value={val}
          onChange={e=>setVal(e.target.value)}
          onKeyDown={e=>{ if(e.key==='Enter'){ onRun(val); }}}
        />
      </div>
      <div style={{display:'flex', gap:6, justifyContent:'flex-end'}}>
        <button className="btn" onClick={()=>onRun(val)}>OK</button>
        <button className="btn" onClick={onClose}>Cancel</button>
      </div>
      <div style={{fontSize:10, color:'#404040', borderTop:'1px solid #ccc', paddingTop:6}}>
        <b>Try:</b> matrix · konami · sudo · whoami · about · spotify · projects · resume · hire · clear
      </div>
    </div>
  );
}

/* ===== Welcome ===== */
function WelcomeContent({ openApp, onClose }) {
  const isTouch = typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(max-width: 900px)').matches;
  return (
    <div style={{display:'flex', flexDirection:'column', flex:1, minHeight:0}}>
      <div style={{display:'flex', flex:1, minHeight:0}}>
        <div style={{
          width:140, background:'linear-gradient(180deg, #1F8A5B, #0E2540)',
          color:'#fff', padding:14, display:'flex', flexDirection:'column', justifyContent:'space-between'
        }}>
          <div>
            <div style={{fontSize:24, fontWeight:700, lineHeight:1, letterSpacing:-0.5}}>devarv</div>
            <div style={{fontSize:11, opacity:0.85, marginTop:6}}>ATHARV.OS</div>
          </div>
          <div style={{fontSize:9, opacity:0.7, fontFamily:'Fixedsys, monospace'}}>v1.0 · 2026</div>
        </div>
        <div style={{flex:1, padding:'14px 18px', overflow:'auto'}}>
          <h2 style={{fontSize:18, marginBottom:6}}>Welcome to ATHARV.OS</h2>
          <p style={{fontSize:11, lineHeight:1.5, marginBottom:8}}>I'm Atharv — a <b>Backend &amp; AI Engineer</b>. I build agentic-LLM systems and production backends. This site pretends to be a 1995 OS because that's what I grew up troubleshooting up in the hills — but every icon opens something real, and <b>three of the projects in here are live products I shipped solo.</b></p>
          {isTouch ? (
            <p style={{fontSize:11, lineHeight:1.5, marginBottom:8, color:'#404040'}}>Tap any icon — windows open full-screen on your phone. Use the taskbar at the bottom to switch between them. (On a desktop, the whole scene tilts in 3D.)</p>
          ) : (
            <p style={{fontSize:11, lineHeight:1.5, marginBottom:8, color:'#404040'}}>The scene is tilted on a 3D plane. Drag a window around — it lifts off the desktop. Move your mouse and the world breathes. Press <kbd style={{padding:'1px 4px',border:'1px solid #888',background:'#eee',fontSize:10}}>Win</kbd>+<kbd style={{padding:'1px 4px',border:'1px solid #888',background:'#eee',fontSize:10}}>R</kbd> for the Run box.</p>
          )}
          <h3 style={{fontSize:12, fontWeight:700, marginTop:10}}>Quick start:</h3>
          <ul style={{marginLeft:18, fontSize:11, lineHeight:1.6}}>
            <li><a onClick={()=>{ openApp('about'); onClose(); }} style={{cursor:'pointer'}}>About me</a> — who I am &amp; what I build</li>
            <li><a onClick={()=>{ openApp('mycomputer'); onClose(); }} style={{cursor:'pointer'}}>My Computer</a> — {D.projects.length} projects, live products first</li>
            <li><a onClick={()=>{ openApp('chat'); onClose(); }} style={{cursor:'pointer'}}>devarv.ai</a> — chat with an AI version of me (it actually answers)</li>
            <li><a onClick={()=>{ openApp('hiring'); onClose(); }} style={{cursor:'pointer'}}>HIRING.TXT</a> — I'm open to work · book a 30-min call</li>
            <li><a onClick={()=>{ openApp('resume'); onClose(); }} style={{cursor:'pointer'}}>Resume.pdf</a> — for the recruiter in a hurry</li>
          </ul>
          <p style={{fontSize:10, lineHeight:1.5, marginTop:10, color:'#606060'}}>Psst — right-click <b>Rover</b> (the dog, bottom-right) and pick <i>“Take the tour”</i> and he'll walk you through it.</p>
        </div>
      </div>
      <div style={{padding:8, borderTop:'1px solid #fff', display:'flex', gap:6, justifyContent:'flex-end', background:'#C0C0C0'}}>
        <button className="btn" onClick={onClose}>Close</button>
      </div>
    </div>
  );
}

/* ===== Contact Form ===== */
function ContactForm() {
  const initial = { name: '', email: '', subject: 'Hello from ATHARV.OS', message: '', botcheck: '' };
  const [form, setForm] = React.useState(initial);
  const [status, setStatus] = React.useState('idle'); // idle | submitting | success | error
  const [errorMsg, setErrorMsg] = React.useState('');

  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const resetForm = () => { setForm(initial); setStatus('idle'); setErrorMsg(''); };

  const onSubmit = async (e) => {
    e.preventDefault();
    if (form.botcheck) return; // honeypot
    if (!form.name.trim()) return setErrorMsg('Name is required');
    if (!/^\S+@\S+\.\S+$/.test(form.email)) return setErrorMsg('Valid email is required');
    if (form.message.trim().length < 10) return setErrorMsg('Message must be at least 10 characters');

    setStatus('submitting');
    setErrorMsg('');

    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          access_key: window.AOS_CONFIG.WEB3FORMS_ACCESS_KEY,
          from_name: 'ATHARV.OS Contact Form',
          name: form.name,
          email: form.email,
          subject: form.subject || 'Hello from ATHARV.OS',
          message: form.message,
          botcheck: form.botcheck,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setStatus('success');
        if (window.sfx && window.sfx.tada) window.sfx.tada();
        if (window.bevelReact) window.bevelReact('jump', "Sent! He'll see it.");
      } else {
        throw new Error(data.message || 'Submission failed');
      }
    } catch (err) {
      setStatus('error');
      setErrorMsg(err.message || 'Network error');
      if (window.sfx && window.sfx.ding) window.sfx.ding();
      if (window.bevelReact) window.bevelReact('tilt', 'Hmm. Try again?');
    }
  };

  if (status === 'success') {
    return (
      <div className="run-dialog" aria-live="polite" style={{maxWidth:420, margin:'0 auto', textAlign:'center'}}>
        <p style={{fontSize:13, margin:0}}>Message sent.</p>
        <p style={{fontSize:11, color:'#404040', margin:0}}>Atharv will reply within ~24 hours.</p>
        <div style={{display:'flex', gap:6, justifyContent:'flex-end'}}>
          <button className="btn" onClick={resetForm}>Send another</button>
        </div>
      </div>
    );
  }

  const disabled = status === 'submitting';
  const showError = !!errorMsg;
  const showNetworkHint = status === 'error';

  return (
    <form onSubmit={onSubmit} className="run-dialog">
      <input
        type="text" name="botcheck" tabIndex={-1} aria-hidden="true"
        value={form.botcheck} onChange={e=>update('botcheck', e.target.value)}
        style={{position:'absolute', left:'-9999px'}}
        autoComplete="off"
      />
      <div className="row">
        <label htmlFor="cf-name" style={{fontSize:11, width:80}}>Name:</label>
        <input id="cf-name" className="w95-input" type="text" required disabled={disabled}
          value={form.name} onChange={e=>update('name', e.target.value)}/>
      </div>
      <div className="row">
        <label htmlFor="cf-email" style={{fontSize:11, width:80}}>Email:</label>
        <input id="cf-email" className="w95-input" type="email" required disabled={disabled}
          value={form.email} onChange={e=>update('email', e.target.value)}/>
      </div>
      <div className="row">
        <label htmlFor="cf-subject" style={{fontSize:11, width:80}}>Subject:</label>
        <input id="cf-subject" className="w95-input" type="text" disabled={disabled}
          value={form.subject} onChange={e=>update('subject', e.target.value)}/>
      </div>
      <div className="row" style={{alignItems:'flex-start'}}>
        <label htmlFor="cf-message" style={{fontSize:11, width:80, paddingTop:4}}>Message:</label>
        <textarea id="cf-message" className="w95-input" rows={6} required disabled={disabled}
          value={form.message} onChange={e=>update('message', e.target.value)}
          style={{flex:1, fontFamily:'inherit'}}/>
      </div>
      {showError && (
        <div role="alert" aria-live="assertive" style={{
          background:'#FFFFCC', border:'2px ridge #c0c0c0',
          padding:8, fontSize:12, color:'#000', marginTop:4
        }}>
          ⚠ {errorMsg}{showNetworkHint ? `. Or email ${window.AOS_CONFIG.CONTACT_EMAIL} directly.` : ''}
        </div>
      )}
      <div style={{display:'flex', gap:6, justifyContent:'flex-end', marginTop:8}}>
        <button type="button" className="btn" onClick={resetForm} disabled={disabled}>Clear</button>
        <button type="submit" className="btn" disabled={disabled}>
          {disabled ? 'Sending...' : 'Send'}
        </button>
      </div>
    </form>
  );
}

/* ===== HIRING.TXT ===== */
function HiringContent() {
  const H = D.hiring;
  if (!H) return <div className="wbody white" style={{padding:14}}>Not hiring info available.</div>;
  const kv = [
    ['Location:', H.location],
    ['Based in:', H.based],
    ['Start:', H.startBy],
    ['Compensation:', `${H.comp.target} — ${H.comp.note}`],
  ];
  return (
    <div className="wbody white" style={{padding:0, overflow:'auto'}}>
      {/* Status banner */}
      <div style={{
        background:'#0a3d0a', color:'#7FFF7F', padding:'10px 14px',
        display:'flex', alignItems:'center', gap:10, borderBottom:'2px solid #000',
        fontFamily:'Fixedsys, Consolas, monospace',
      }}>
        <span style={{
          width:10, height:10, borderRadius:'50%', background:'#39FF39',
          boxShadow:'0 0 6px #39FF39', animation:'trayPulse 1.4s ease-in-out infinite', flexShrink:0,
        }}/>
        <div>
          <div style={{fontSize:15, fontWeight:700, letterSpacing:1}}>{H.status}</div>
          <div style={{fontSize:10, opacity:0.8}}>{H.subStatus} · updated {H.updated}</div>
        </div>
      </div>
      <div style={{padding:'12px 14px', fontSize:11, lineHeight:1.5}}>
        {/* Roles */}
        <h3 style={{fontSize:12, fontWeight:700, marginBottom:4}}>Looking for</h3>
        <div className="tag-row" style={{marginBottom:2}}>
          {H.roles.map((r,i) => <span className="tag" key={i} style={{fontWeight:700}}>{r}</span>)}
        </div>
        <div style={{color:'#404040', marginBottom:10}}>{H.seniority}</div>
        {/* Facts */}
        <div style={{display:'grid', gridTemplateColumns:'110px 1fr', gap:'4px 10px', marginBottom:10}}>
          {kv.map(([k,v],i) => <React.Fragment key={i}><span style={{color:'#404040'}}>{k}</span><span>{v}</span></React.Fragment>)}
        </div>
        {/* Stack */}
        <h3 style={{fontSize:12, fontWeight:700, marginBottom:4}}>Stack</h3>
        <div className="tag-row" style={{marginBottom:10}}>
          {H.stack.map((s,i) => <span className="tag" key={i}>{s}</span>)}
        </div>
        {/* Proof */}
        <h3 style={{fontSize:12, fontWeight:700, marginBottom:4}}>Proof of work — live in production</h3>
        <div style={{display:'flex', flexDirection:'column', gap:4, marginBottom:12}}>
          {H.proof.map((p,i) => (
            <div key={i} style={{display:'flex', alignItems:'center', gap:8, padding:'4px 6px', border:'1px solid #ccc', background:'#fafafa'}}>
              <div style={{flex:1, minWidth:0}}>
                <b>{p.name}</b> <span style={{color:'#404040'}}>— {p.note}</span>
              </div>
              <a className="btn" href={p.url} target="_blank" rel="noreferrer" style={{flexShrink:0, textDecoration:'none', color:'#000'}}>🌐 Live</a>
            </div>
          ))}
        </div>
        {/* CTA */}
        <div style={{borderTop:'1px solid #ccc', paddingTop:10, display:'flex', gap:6, flexWrap:'wrap'}}>
          <a className="btn" href={`mailto:${H.cta.email}?subject=Opportunity%20for%20Atharv`} onClick={()=>window.va&&window.va('event',{name:'click_email',data:{from:'hiring'}})} style={{textDecoration:'none', color:'#000', fontWeight:700}}>📧 Email me</a>
          {H.cta.call && <a className="btn" href={H.cta.call} target="_blank" rel="noreferrer" onClick={()=>window.va&&window.va('event',{name:'book_call'})} style={{textDecoration:'none', color:'#000', fontWeight:700}}>📅 Book a call</a>}
          <a className="btn" href={H.cta.linkedin} target="_blank" rel="noreferrer" style={{textDecoration:'none', color:'#000'}}>💼 LinkedIn</a>
          <a className="btn" href={H.cta.github} target="_blank" rel="noreferrer" style={{textDecoration:'none', color:'#000'}}>🐙 GitHub</a>
          <a className="btn" href={H.cta.resume} download="Atharv-Sharma-Resume.pdf" onClick={()=>window.va&&window.va('event',{name:'download_resume',data:{from:'hiring'}})} style={{textDecoration:'none', color:'#000'}}>📄 Resume</a>
          <a className="btn" href="assets/atharv-sharma.vcf" download="Atharv-Sharma.vcf" onClick={()=>window.va&&window.va('event',{name:'download_vcard'})} style={{textDecoration:'none', color:'#000'}}>📇 Save contact</a>
        </div>
        <div style={{marginTop:8, fontSize:10, color:'#808080'}}>Replies within 24 hours. Or just ask devarv.ai — it knows my work.</div>
      </div>
    </div>
  );
}

/* ===== Guestbook (email-only via Web3Forms) ===== */
function GuestbookForm() {
  const initial = { name: '', location: '', website: '', message: '', botcheck: '' };
  const [form, setForm] = React.useState(initial);
  const [status, setStatus] = React.useState('idle');
  const [errorMsg, setErrorMsg] = React.useState('');
  const hits = (() => {
    try { return parseInt(localStorage.getItem('aos-gb-hits') || '1337', 10); } catch (e) { return 1337; }
  })();

  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const onSubmit = async (e) => {
    e.preventDefault();
    if (form.botcheck) return;
    if (!form.name.trim()) return setErrorMsg('Name is required');
    if (form.message.trim().length < 5) return setErrorMsg('Say a little more than that :)');
    setStatus('submitting');
    setErrorMsg('');
    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          access_key: window.AOS_CONFIG.WEB3FORMS_ACCESS_KEY,
          from_name: 'ATHARV.OS Guestbook',
          subject: 'Guestbook entry — ATHARV.OS',
          name: form.name,
          location: form.location || '(not given)',
          website: form.website || '(not given)',
          message: form.message,
          botcheck: form.botcheck,
        }),
      });
      const data = await res.json();
      if (!data.success) throw new Error(data.message || 'Submission failed');
      try { localStorage.setItem('aos-gb-hits', String(hits + 1)); } catch (e) {}
      setStatus('success');
      if (window.sfx && window.sfx.tada) window.sfx.tada();
    } catch (err) {
      setStatus('idle');
      setErrorMsg(`${err.message || 'Network error'}. Or email ${window.AOS_CONFIG.CONTACT_EMAIL} directly.`);
    }
  };

  if (status === 'success') {
    return (
      <div style={{ textAlign: 'center', padding: 20, fontFamily: '"Times New Roman", serif' }}>
        <h2 style={{ color: '#000080' }}>★ Thank you for signing my guestbook! ★</h2>
        <p style={{ fontSize: 13, marginTop: 8 }}>Your entry has been delivered to Atharv's inbox.</p>
        <p style={{ fontSize: 26, margin: '14px 0', fontFamily: 'Fixedsys, monospace', background: '#000', color: '#00FF00', display: 'inline-block', padding: '4px 14px', letterSpacing: 4 }}>
          {String(hits + 1).padStart(6, '0')}
        </p>
        <p style={{ fontSize: 11, color: '#808080' }}>visitors have signed this page</p>
        <button className="btn" style={{ marginTop: 12 }} onClick={() => { setForm(initial); setStatus('idle'); }}>Sign again</button>
      </div>
    );
  }

  const disabled = status === 'submitting';
  return (
    <form onSubmit={onSubmit} className="run-dialog" style={{ maxWidth: 480 }}>
      <input type="text" name="botcheck" tabIndex={-1} aria-hidden="true"
        value={form.botcheck} onChange={e => update('botcheck', e.target.value)}
        style={{ position: 'absolute', left: '-9999px' }} autoComplete="off"/>
      <div className="row">
        <label htmlFor="gb-name" style={{ fontSize: 11, width: 80 }}>Name:</label>
        <input id="gb-name" className="w95-input" type="text" required disabled={disabled}
          value={form.name} onChange={e => update('name', e.target.value)}/>
      </div>
      <div className="row">
        <label htmlFor="gb-loc" style={{ fontSize: 11, width: 80 }}>Location:</label>
        <input id="gb-loc" className="w95-input" type="text" placeholder="optional" disabled={disabled}
          value={form.location} onChange={e => update('location', e.target.value)}/>
      </div>
      <div className="row">
        <label htmlFor="gb-web" style={{ fontSize: 11, width: 80 }}>Homepage:</label>
        <input id="gb-web" className="w95-input" type="text" placeholder="optional" disabled={disabled}
          value={form.website} onChange={e => update('website', e.target.value)}/>
      </div>
      <div className="row" style={{ alignItems: 'flex-start' }}>
        <label htmlFor="gb-msg" style={{ fontSize: 11, width: 80, paddingTop: 4 }}>Message:</label>
        <textarea id="gb-msg" className="w95-input" rows={4} required disabled={disabled}
          value={form.message} onChange={e => update('message', e.target.value)}
          style={{ flex: 1, fontFamily: 'inherit' }}/>
      </div>
      {errorMsg && (
        <div role="alert" style={{ background: '#FFFFCC', border: '2px ridge #c0c0c0', padding: 8, fontSize: 12 }}>
          ⚠ {errorMsg}
        </div>
      )}
      <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end', marginTop: 8 }}>
        <button type="submit" className="btn" disabled={disabled}>
          {disabled ? 'Signing…' : '✍ Sign guestbook'}
        </button>
      </div>
    </form>
  );
}

/* ===== Internet Explorer ===== */
function IEContent() {
  const [url, setUrl] = React.useState('http://www.atharv.os/home');
  const [input, setInput] = React.useState('http://www.atharv.os/home');
  const [history, setHistory] = React.useState(['http://www.atharv.os/home']);
  const [idx, setIdx] = React.useState(0);
  const go = (u) => {
    const next = history.slice(0, idx + 1).concat(u);
    setHistory(next); setIdx(next.length - 1); setUrl(u); setInput(u);
  };
  const back = () => { if (idx > 0) { setIdx(idx-1); setUrl(history[idx-1]); setInput(history[idx-1]); } };
  const fwd = () => { if (idx < history.length-1) { setIdx(idx+1); setUrl(history[idx+1]); setInput(history[idx+1]); } };
  const goRef = React.useRef();
  goRef.current = go;
  React.useEffect(() => {
    const h = (e) => {
      const target = e.detail && e.detail.url;
      if (target && goRef.current) goRef.current(target);
    };
    window.addEventListener('atharv-os:ie-navigate', h);
    return () => window.removeEventListener('atharv-os:ie-navigate', h);
  }, []);
  const pages = {
    'http://www.atharv.os/home': (
      <div style={{padding:20, fontFamily:'"Times New Roman", serif', color:'#000'}}>
        <h1 style={{fontSize:28, color:'#000080', borderBottom:'2px solid #000080'}}>Welcome to ATHARV.OS</h1>
        <p style={{fontSize:14, marginTop:10}}>The personal homepage of <b>Atharv Sharma</b> on the World Wide Web!</p>
        <p style={{fontSize:13, marginTop:10}}>This page is best viewed in 800×600 resolution at 256 colors.</p>
        <ul style={{fontSize:13, marginTop:14, marginLeft:20}}>
          <li><a href="#" onClick={(e)=>{e.preventDefault(); go('http://www.atharv.os/projects');}} style={{color:'#0000EE'}}>My Projects</a></li>
          <li><a href="#" onClick={(e)=>{e.preventDefault(); go('http://www.atharv.os/contact');}} style={{color:'#0000EE'}}>Contact</a></li>
          <li><a href="#" onClick={(e)=>{e.preventDefault(); go('http://www.atharv.os/guestbook');}} style={{color:'#0000EE'}}>✍ Sign my Guestbook!</a></li>
          <li><a href="#" onClick={(e)=>{e.preventDefault(); go('http://www.atharv.os/links');}} style={{color:'#0000EE'}}>Cool Links</a></li>
        </ul>
        <p style={{fontSize:11, marginTop:30, color:'#808080'}}>Last updated: Today | Visitors: 000042</p>
        <div style={{
          marginTop:20, padding:12, border:'2px ridge #c0c0c0',
          background:'#FFFFCC', fontSize:13, textAlign:'center'
        }}>
          Want to get in touch?
          <br />
          <button
            className="btn"
            style={{ marginTop:8, minWidth:120 }}
            onClick={() => go('http://www.atharv.os/contact')}
          >
            ✉ Contact Atharv →
          </button>
        </div>
      </div>
    ),
    'http://www.atharv.os/projects': (
      <div style={{padding:20, fontFamily:'"Times New Roman", serif'}}>
        <h1 style={{fontSize:24, color:'#000080'}}>Projects</h1>
        <p style={{fontSize:13}}>See <b>My Computer</b> on the desktop for the full list.</p>
      </div>
    ),
    'http://www.atharv.os/contact': (
      <div style={{ padding: 18 }}>
        <h2 style={{ marginTop: 0, fontFamily: '"Times New Roman", serif' }}>
          Contact Atharv
        </h2>
        <p style={{ fontSize: 13, color: '#404040', marginBottom: 16 }}>
          Drop a message — for hiring, collaboration, or just to say hi.
          Replies usually within 24 hours.
        </p>
        <ContactForm />
      </div>
    ),
    'http://www.atharv.os/guestbook': (
      <div style={{ padding: 18 }}>
        <h2 style={{ marginTop: 0, fontFamily: '"Times New Roman", serif', color: '#000080' }}>
          ✍ My Guestbook
        </h2>
        <p style={{ fontSize: 13, color: '#404040', marginBottom: 14 }}>
          Like the old web, but the entries land in my inbox. Leave your mark, traveller.
        </p>
        <GuestbookForm />
      </div>
    ),
    'http://www.atharv.os/links': (
      <div style={{padding:20, fontFamily:'"Times New Roman", serif'}}>
        <h1 style={{fontSize:24, color:'#000080'}}>Cool Links</h1>
        <ul style={{fontSize:13, marginLeft:20}}>
          <li><a href={D.identity.github} target="_blank" style={{color:'#0000EE'}}>GitHub</a></li>
          <li><a href={D.identity.linkedin} target="_blank" style={{color:'#0000EE'}}>LinkedIn</a></li>
        </ul>
      </div>
    ),
  };
  return (
    <div className="wbody" style={{padding:0, display:'flex', flexDirection:'column', height:'100%'}}>
      <div style={{display:'flex', gap:4, padding:4, borderBottom:'1px solid #808080', background:'#c0c0c0'}}>
        <button className="tbbtn" onClick={back} disabled={idx===0}>◀ Back</button>
        <button className="tbbtn" onClick={fwd} disabled={idx===history.length-1}>Forward ▶</button>
        <button className="tbbtn" onClick={()=>go('http://www.atharv.os/home')}>🏠 Home</button>
      </div>
      <div style={{display:'flex', alignItems:'center', gap:6, padding:4, borderBottom:'1px solid #808080', background:'#c0c0c0', fontSize:11}}>
        <span>Address:</span>
        <input value={input} onChange={e=>setInput(e.target.value)}
          onKeyDown={e=>{if(e.key==='Enter') go(input);}}
          style={{flex:1, padding:'2px 4px', border:'1px solid #808080', fontFamily:'inherit'}}/>
      </div>
      <div style={{flex:1, overflow:'auto', background:'#fff'}}>
        {pages[url] || <div style={{padding:20}}>Page not found.</div>}
      </div>
      <div style={{padding:'2px 6px', borderTop:'1px solid #808080', background:'#c0c0c0', fontSize:10, color:'#000'}}>
        Done · Internet zone
      </div>
    </div>
  );
}

/* Export to global scope */
Object.assign(window, {
  Ico, AboutContent, ProjectContent, ExperienceContent, SkillsContent,
  AwardsContent, PhotosContent, NotesContent, NetworkContent, IEContent, ResumeContent,
  RunDialog, WelcomeContent, ContactForm, HiringContent, GuestbookForm
});
