/* ============ 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">Phone:</span><span>{D.identity.phone}</span>
              <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-a3b6a0251</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.securepass} target="_blank" rel="noreferrer">SecurePass Vault</a> · <a href={D.identity.cybercordon} target="_blank" rel="noreferrer">Cyber Cordon</a> · <a href={D.identity.megoforex} target="_blank" rel="noreferrer">Mego Forex</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'},
    {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==='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 ===== */
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("${p.file}")`, 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("${p.file}")`, 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 items = [
    { name: 'GitHub', icon: 'github', url: D.identity.github },
    { name: 'LinkedIn', icon: 'linkedin', url: D.identity.linkedin },
    { name: 'SecurePass Vault', icon: 'globe', url: D.identity.securepass },
    { name: 'Cyber Cordon', icon: 'globe', url: D.identity.cybercordon },
    { name: 'Mego Forex', icon: 'globe', url: D.identity.megoforex },
    { name: 'Email atharv@', icon: 'email', url: `mailto:${D.identity.email}` },
    { name: 'Phone', icon: 'phone', url: `tel:${D.identity.phone}` },
  ];
  return (
    <div className="wbody white" style={{padding:0}}>
      <div className="netgrid">
        {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>
  );
}

/* ===== 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">💾 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 }) {
  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}}>This is a portfolio. It pretends to be a 1995 operating system because that's the OS I grew up troubleshooting. Click around — every icon opens something real.</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</li>
            <li><a onClick={()=>{ openApp('mycomputer'); onClose(); }} style={{cursor:'pointer'}}>My Computer</a> — 14 production projects</li>
            <li><a onClick={()=>{ openApp('mediaplayer'); onClose(); }} style={{cursor:'pointer'}}>Media Player</a> — what I'm listening to right now</li>
            <li><a onClick={()=>{ openApp('resume'); onClose(); }} style={{cursor:'pointer'}}>Resume.pdf</a> — for the recruiter in a hurry</li>
          </ul>
        </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>
  );
}

/* ===== 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/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/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
});
