// Dossier v2 main component.

// Acronym glossary - hover any matched term in text for definition.
const ACRONYMS = {
  "SysML": "Systems Modeling Language — a graphical modeling language standardized by OMG for systems engineering",
  "MBSE": "Model-Based Systems Engineering — formalized application of modeling to systems engineering activities",
  "UAF": "Unified Architecture Framework — OMG-standardized framework for enterprise/system architecture",
  "RMF": "Risk Management Framework — NIST process for managing cybersecurity risk in federal systems",
  "ATO": "Authorization to Operate — formal approval for a system to operate in production",
  "cATO": "Continuous Authorization to Operate — automated, ongoing ATO process",
  "NMCI": "Navy Marine Corps Intranet — the U.S. Navy's enterprise IT network",
  "COMSEC": "Communications Security — measures to deny unauthorized access to communications",
  "TACLANE": "Tactical Local Area Network Encryptor — Type 1 encryption device",
  "NIST": "National Institute of Standards and Technology",
  "DoD": "Department of Defense",
  "V&V": "Verification & Validation — the V-model lifecycle phase for testing and validation",
  "OMG": "Object Management Group — standards body for SysML, UAF, etc.",
  "INCOSE": "International Council on Systems Engineering",
  "OCSMP": "OMG-Certified Systems Modeling Professional",
  "LAN": "Local Area Network",
  "WAN": "Wide Area Network",
  "EDR": "Endpoint Detection and Response",
  "IA": "Information Assurance — managing and protecting the confidentiality, integrity, and availability of information systems",
  "IT": "Information Technology",
  "CCST": "Cisco Certified Support Technician",
  "CompTIA": "Computing Technology Industry Association — IT industry certification body",
  "AZ-900": "Microsoft Azure Fundamentals — entry-level Azure cloud certification"
};

// Expose for the command-palette glossary (separate Babel scope).
window.ACRONYMS = ACRONYMS;

// Tracks which acronyms have already been highlighted in the current render.
// Only the FIRST occurrence of each term gets a tooltip; later ones render
// as plain text. Reset at the top of every DossierV2 render (see below).
const seenAcronyms = new Set();

// Wrap matched acronyms in <Term> for hover tooltips
function withAcronyms(text) {
  if (typeof text !== 'string') return text;
  const keys = Object.keys(ACRONYMS).sort((a, b) => b.length - a.length);
  const pattern = new RegExp('\\b(' + keys.map((k) => k.replace(/[+&]/g, '\\$&')).join('|') + ')\\b', 'g');
  const parts = [];
  let lastIndex = 0;
  let match;
  let key = 0;
  while ((match = pattern.exec(text)) !== null) {
    if (match.index > lastIndex) parts.push(text.slice(lastIndex, match.index));
    const term = match[0];
    if (seenAcronyms.has(term)) {
      // Already introduced earlier on the page — render plain, no tooltip.
      parts.push(term);
    } else {
      seenAcronyms.add(term);
      parts.push(
        <span key={key++} className="term" data-def={ACRONYMS[term]} tabIndex={0}>{term}</span>
      );
    }
    lastIndex = match.index + term.length;
  }
  if (lastIndex < text.length) parts.push(text.slice(lastIndex));
  return parts.length ? parts : text;
}

const TOC_ITEMS = [
{ id: 'about', label: 'About', icon: 'user' },
{ id: 'domains', label: 'Disciplines × Lifecycle', icon: 'grid' },
{ id: 'projects', label: 'Selected Work', icon: 'folder' },
{ id: 'experience', label: 'Service Record', icon: 'activity' },
{ id: 'skills', label: 'Capabilities', icon: 'cpu' },
{ id: 'writing', label: 'Field Notes', icon: 'notebook' },
{ id: 'now', label: 'Now', icon: 'radio' },
{ id: 'contact', label: 'Comms', icon: 'mail' }];


// Current month/year, formatted like "MAY 2026" / "May 2026".
// Auto-updates whenever the page loads, so date stamps stay current
// without manual maintenance.
const NOW_DATE = new Date();
const CURRENT_MONTH_UPPER = NOW_DATE.toLocaleString('en-US', { month: 'long', year: 'numeric' }).toUpperCase();
const CURRENT_MONTH_TITLE = NOW_DATE.toLocaleString('en-US', { month: 'long', year: 'numeric' });

function DossierV2({ theme = 'dark', onThemeChange, heroCopy }) {
  DossierV2Styles();

  // Reset first-occurrence tracking each render so only the first mention of
  // each acronym (in document order) gets a tooltip.
  seenAcronyms.clear();

  // Mirror theme to localStorage so the inline pre-paint script can read it on next load
  React.useEffect(() => {
    try {
      localStorage.setItem('dossier-theme', theme);
      document.documentElement.setAttribute('data-theme', theme);
    } catch (e) {}
  }, [theme]);

  const D = window.SITE_DATA;
  const [filter, setFilter] = React.useState('ALL');
  const [openId, setOpenId] = React.useState(null);
  const [active, setActive] = React.useState('about');
  const [cmdOpen, setCmdOpen] = React.useState(false);
  const [scrollProgress, setScrollProgress] = React.useState(0);
  const [toast, setToast] = React.useState(null);
  const [liveTime, setLiveTime] = React.useState(() =>
  new Date().toLocaleString('en-US', { timeZone: 'America/New_York', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }).replace(',', '')
  );

  // Keyboard section nav — j/k jump to next/previous section
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.metaKey || e.ctrlKey || e.altKey) return;
      if (e.key !== 'j' && e.key !== 'k') return;
      const t = e.target;
      const tag = (t.tagName || '').toLowerCase();
      if (tag === 'input' || tag === 'textarea' || t.isContentEditable) return;
      const sections = TOC_ITEMS.map((it) => document.getElementById(it.id)).filter(Boolean);
      if (!sections.length) return;
      const pos = window.scrollY + 80;
      let idx = -1;
      for (let i = 0; i < sections.length; i++) {
        if (sections[i].offsetTop <= pos + 2) idx = i;
      }
      e.preventDefault();
      if (e.key === 'k' && idx <= 0) {
        window.scrollTo({ top: 0, behavior: 'smooth' });
        return;
      }
      const next = e.key === 'j' ? Math.min(idx + 1, sections.length - 1) : idx - 1;
      const target = sections[next];
      if (target) window.scrollTo({ top: target.offsetTop - 60, behavior: 'smooth' });
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  // Live clock - updates every 10 seconds
  React.useEffect(() => {
    const tick = () => {
      setLiveTime(
        new Date().toLocaleString('en-US', { timeZone: 'America/New_York', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }).replace(',', '')
      );
    };
    const interval = setInterval(tick, 10000);
    return () => clearInterval(interval);
  }, []);

  // Hide reveal targets synchronously BEFORE browser paints (useLayoutEffect)
  React.useLayoutEffect(() => {
    const targets = document.querySelectorAll(
      '.dv2 .sec-head, .dv2 .proj, .dv2 .skills > div, .dv2 .tl > *, .dv2 .write-row, .dv2 .now-card, .dv2 .contact-block, .dv2 .matrix, .dv2 .about, .dv2 .contact-block .links a, .dv2 .toc'
    );
    targets.forEach((el) => el.classList.add('scroll-reveal'));
  }, []);

  // Scroll-triggered reveal animations — observer adds in-view on intersection
  React.useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add('in-view');
        }
      });
    }, { threshold: 0.05, rootMargin: '0px 0px -30px 0px' });

    const targets = document.querySelectorAll('.dv2 .scroll-reveal');
    // Small delay so initial opacity:0 state is painted before observation starts
    const timer = setTimeout(() => {
      targets.forEach((el) => observer.observe(el));
    }, 80);

    return () => {
      clearTimeout(timer);
      observer.disconnect();
    };
  }, []);

  // Reading progress bar - tracks scroll depth
  React.useEffect(() => {
    const update = () => {
      const docHeight = document.documentElement.scrollHeight - window.innerHeight;
      const progress = docHeight > 0 ? window.scrollY / docHeight * 100 : 0;
      setScrollProgress(Math.min(100, Math.max(0, progress)));
    };
    update();
    window.addEventListener('scroll', update, { passive: true });
    window.addEventListener('resize', update);
    return () => {
      window.removeEventListener('scroll', update);
      window.removeEventListener('resize', update);
    };
  }, []);

  // Toast helper - shows confirmation message
  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(null), 2000);
  };

  // Copy to clipboard with toast feedback
  const copyToClipboard = (text, label) => {
    navigator.clipboard?.writeText(text).then(() => {
      showToast(`${label} copied to clipboard`);
    }).catch(() => {
      showToast('Copy failed');
    });
  };

  // Copy section deep-link to clipboard
  const copySectionLink = (id) => {
    const url = `${window.location.origin}${window.location.pathname}#${id}`;
    copyToClipboard(url, 'Section link');
  };

  // Allow the command palette to open a specific project case study.
  React.useEffect(() => {
    const onOpen = (e) => {
      setOpenId(e.detail);
      // Wait a tick so the section is in the DOM, then scroll the project itself into view.
      setTimeout(() => {
        const el = document.querySelector(`.proj[data-pid="${e.detail}"]`);
        if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }, 100);
    };
    window.addEventListener('dossier:open-project', onOpen);
    return () => window.removeEventListener('dossier:open-project', onOpen);
  }, []);

  const allTags = ['ALL', ...new Set(D.projects.flatMap((p) => p.tags))];
  const filtered = filter === 'ALL' ? D.projects : D.projects.filter((p) => p.tags.includes(filter));

  // scroll spy: pick the section whose top is closest above the viewport's
  // 25% line. This is bidirectional-stable — IntersectionObserver with a
  // narrow band misses short sections near the page bottom when scrolling up.
  React.useEffect(() => {
    let raf = 0;
    const update = () => {
      raf = 0;
      const probe = window.innerHeight * 0.25;
      let bestId = TOC_ITEMS[0].id;
      let bestTop = -Infinity;
      for (const t of TOC_ITEMS) {
        const el = document.getElementById(t.id);
        if (!el) continue;
        const top = el.getBoundingClientRect().top;
        if (top <= probe && top > bestTop) {
          bestTop = top;
          bestId = t.id;
        }
      }
      // Bottom-of-page guard: if the user is within 80px of the page bottom,
      // force-activate the last TOC item so Comms doesn't get skipped.
      const scrolledToBottom = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 80;
      if (scrolledToBottom) bestId = TOC_ITEMS[TOC_ITEMS.length - 1].id;
      setActive(bestId);
    };
    const onScroll = () => {if (!raf) raf = requestAnimationFrame(update);};
    update();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  // domain matrix: MBSE-forward. Networks/IT are present but supporting.
  // Disciplines (rows) × Lifecycle stage (cols). Coverage reflects
  // where I'm actually hands-on across the V: strongest mid-cycle
  // (requirements → architecture → V&V), supporting at the edges.
  const domainCols = ['Concept', 'Requirements', 'Architecture', 'Integration', 'Sustainment'];
  const domainRows = [
  { row: 'SysML modeling', vals: [0.5, 1, 1, 1, 0.5] },
  { row: 'UAF architecture', vals: [0, 1, 1, 0, 0] },
  { row: 'Requirements & traceability', vals: [0.5, 1, 1, 0.5, 0.5] },
  { row: 'Verification & Validation', vals: [0, 0.5, 0.5, 1, 0.5] },
  { row: 'Pattern & template authoring', vals: [0, 0.5, 1, 0.5, 1] }];


  return (
    <div className={'dv2 ' + (theme === 'light' ? 'light' : '')}>
      {/* Floating particle background — fewer particles on mobile */}
      <Particles
        count={typeof window !== 'undefined' && window.innerWidth < 768 ? 25 : 70}
        color={theme === 'light' ? '#2a7569' : '#5dd4c4'}
        lineAlpha={theme === 'light' ? 0.32 : 0.2}
        particleAlphaMin={theme === 'light' ? 0.22 : 0.15}
        particleAlphaMax={theme === 'light' ? 0.55 : 0.5} />
      

      {/* Reading progress bar */}
      <div className="progress-bar" style={{ width: `${scrollProgress}%` }}></div>

      {/* Toast notification */}
      {toast && <div className="toast">{toast}</div>}

      <span className="frame-corner tl"></span>
      <span className="frame-corner tr"></span>
      <span className="frame-corner bl"></span>
      <span className="frame-corner br"></span>

      <div className="topbar">
        <div className="l">
          <span>MATTHEW BUNN</span>
          <span>SYSTEMS ENGINEER</span>
          <div className="search-box" onClick={() => setCmdOpen(true)} title="Open command palette">
            <span className="search-icon">⌕</span>
            <span className="search-text">Search</span>
            <span className="kbd">⌘K</span>
          </div>
          <button className="theme-toggle" onClick={() => onThemeChange && onThemeChange(theme === 'dark' ? 'light' : 'dark')} title="Toggle theme">
            {theme === 'dark' ? '☀' : '☾'}
          </button>
          <button className="print-btn" onClick={() => window.print()} title="Print dossier">
            <Icon name="print" />
          </button>
        </div>
        <div className="c"><span className="glyph">⌖</span> MATTHEW BUNN · SYSTEMS DOSSIER</div>
        <div className="r">
          <a href="Resume.html"><Icon name="download" /> RESUME</a>
          <a href={`https://${D.contact.linkedin}`}><Icon name="external" /> LINKEDIN</a>
          <a href={`mailto:${D.contact.email}`}><Icon name="mail" /> CONTACT</a>
        </div>
      </div>

      <div className="shell">
        {/* TOC */}
        <aside className="toc">
          <h5>Table of Contents</h5>
          <ol>
            {TOC_ITEMS.map((t) =>
            <li key={t.id}>
                <a href={'#' + t.id} className={active === t.id ? 'active' : ''}>{t.label}</a>
              </li>
            )}
          </ol>
          <div className="meta">
            <b>STATUS</b><br />
            <span style={{ color: 'var(--signal)' }}><span className="live-dot"></span>OPEN TO WORK</span><br /><br />
            <b>BASE</b><br />{D.location}<br /><br />
            <b>CLEARED</b><br />ACTIVE SECRET<br /><br />
            <b>CERTS</b><br />Sec+ · AZ-900 · CCST<br /><br />
            <a href="Resume.html" className="act"><Icon name="download" /> RESUME</a>
          </div>
        </aside>

        <main className="main">
          {/* HERO */}
          <section className="hero">
            <div>
              <div className="kicker reveal d1">MBSE SYSTEMS ENGINEER · G2 OPS · {CURRENT_MONTH_UPPER}</div>
              <h1 className="reveal d2">
                Systems engineering,<br /><em>captured in models.</em>
              </h1>
              <p className="lead reveal d3">
                I'm <b>Matthew Bunn</b>, an MBSE Systems Engineer at G2 Ops. I work across the
                lifecycle in SysML and the Unified Architecture Framework, from requirements
                through architecture to the artifacts that downstream activities depend on. Active
                Secret cleared.
              </p>
              <div className="cta-row reveal d4">
                <a className="cta primary" href="#projects"><Icon name="folder" /> Selected Work</a>
                <a className="cta" href="Resume.html"><Icon name="download" /> Resume.pdf</a>
                <a className="cta" href={`mailto:${D.contact.email}`}><Icon name="mail" /> Open Channel</a>
              </div>
            </div>
            <div className="schematic reveal d3">
              <div className="sch-head">
                <span className="l">⌖ FIG. 01</span>
                <span className="r">MBSE ARTIFACT FLOW</span>
              </div>
              <HeroSchematic />
              <div className="sch-foot">
                <span>REQS → MODEL → ARTIFACTS</span>
                <span>SYSML</span>
              </div>
            </div>
          </section>

          {/* ABOUT */}
          <section id="about" className="section">
            <header className="sec-head">
              <div className="num">§ 01</div>
              <div className="title"><span className="ico"><Icon name="user" /></span><h2>About<span className="sub">OPERATOR PROFILE
</span></h2></div>
              <div className="meta">4 PARAGRAPHS<button className="share-btn" onClick={() => copySectionLink('about')} title="Copy link to this section">🔗</button></div>
            </header>
            <div className="about">
              <div>
                {D.about.map((p, i) => <p key={i}>{withAcronyms(p)}{i === 0 ? <a href="#fn-1" className="fnref" data-def="See §02 for where I'm hands-on across the V-model lifecycle. (SysML, UAF, requirements, and V&V.)"><sup>1</sup></a> : i === 2 ? <a href="#fn-2" className="fnref" data-def="Background context: §04, Service Record."><sup>2</sup></a> : null}</p>)}
                <div className="footnotes">
                  <div id="fn-1"><b>1.</b> See §02 for where I'm hands-on across the V-model lifecycle. {withAcronyms("SysML, UAF, requirements, and V&V.")} <a href="#about" className="fnback" title="Back to text">↩</a></div>
                  <div id="fn-2"><b>2.</b> Background context: §04, Service Record. <a href="#about" className="fnback" title="Back to text">↩</a></div>
                </div>
              </div>
              <aside className="about-side">
                <h4>Operating Parameters</h4>
                <div className="row"><span className="k">domain</span><span className="v">{withAcronyms("Navy / DoD / Commercial")}</span></div>
                <div className="row"><span className="k">clearance</span><span className="v">Active Secret</span></div>
                <div className="row"><span className="k">current base</span><span className="v">Virginia
(open to relocation)</span></div>
                <div className="row"><span className="k">work arrangement</span><span className="v">flexible (onsite, hybrid, remote)</span></div>
                <div className="row"><span className="k">certs</span><span className="v">Sec+ · AZ-900 · CCST</span></div>
              </aside>
            </div>
          </section>

          {/* DOMAIN MATRIX */}
          <section id="domains" className="section">
            <header className="sec-head">
              <div className="num">§ 02</div>
              <div className="title"><span className="ico"><Icon name="grid" /></span><h2>Disciplines × Lifecycle<span className="sub">● hands-on  ◐ partial  ○ not in my scope</span></h2></div>
              <div className="meta">{domainRows.length} × {domainCols.length}<button className="share-btn" onClick={() => copySectionLink('domains')} title="Copy link to this section">🔗</button></div>
            </header>
            <p className="matrix-caption">
              <b>Rows:</b> Disciplines I practice. <b>Columns:</b> Stages of the systems-engineering lifecycle (the V-model). <i>How hands-on, where?</i>
            </p>
            <div className="matrix">
              <div className="cell corner"></div>
              {domainCols.map((c) => <div key={c} className="cell col-h">{c}</div>)}
              {domainRows.map((r, i) => <React.Fragment key={i}>
                  <div className="cell row-h">{r.row}</div>
                  {r.vals.map((v, j) => <div key={j} className="cell">
                      {v === 1 ? <span className="dot"></span> :
                  v === 0.5 ? <span className="dot half"></span> :
                  <span className="dot empty"></span>}
                    </div>
                )}
                </React.Fragment>
              )}
            </div>
          </section>

          {/* PROJECTS */}
          <section id="projects" className="section">
            <header className="sec-head">
              <div className="num">§ 03</div>
              <div className="title"><span className="ico"><Icon name="folder" /></span><h2>Selected Work<span className="sub">Click to expand case study</span></h2></div>
              <div className="meta">{filtered.length} of {D.projects.length}<button className="share-btn" onClick={() => copySectionLink('projects')} title="Copy link to this section">🔗</button></div>
            </header>
            <div className="filter-bar">
              {allTags.map((t) =>
              <button key={t} className={'filter ' + (filter === t ? 'active' : '')} onClick={() => setFilter(t)}>{t}</button>
              )}
            </div>
            <div className="proj-list">
              {filtered.map((p) =>
              <article key={p.id} data-pid={p.id} className={'proj ' + (openId === p.id ? 'open' : '')}>
                  <div className="proj-head" onClick={() => setOpenId(openId === p.id ? null : p.id)}>
                    <div className="code">{p.code}</div>
                    <div className="core">
                      <h3>{p.title}</h3>
                      <div className="sm">{withAcronyms(p.summary)}</div>
                      <div className="tags">{p.tags.map((t) => <span key={t} className="tag">{t}</span>)}</div>
                    </div>
                    <div className="metrics">
                      {(p.metrics || []).map((m, i) =>
                    <div key={i} className="metric">
                          <div className="v">{m.v}</div>
                          <div className="k">{m.k}</div>
                        </div>
                    )}
                    </div>
                    <div className="yr">{p.year}</div>
                    <div className="arr"><Icon name="chevronR" /></div>
                  </div>
                  {openId === p.id &&
                <div className="proj-body">
                      <div className="header-band">
                        <span><b>{p.code}</b> · {p.role}</span>
                        <span>{p.domain} · {p.year}</span>
                        <span>CASE STUDY</span>
                      </div>
                      <div className="grid">
                        <div><h5>Problem</h5><p>{withAcronyms(p.problem)}</p></div>
                        <div><h5>Approach</h5><p>{withAcronyms(p.approach)}</p></div>
                        <div><h5>Outcome</h5><p>{withAcronyms(p.outcome)}</p></div>
                      </div>
                      <div className="footer-grid">
                        <div>
                          <h5>Stack</h5>
                          <div className="stack-list">{p.stack.map((s) => <span key={s}>{s}</span>)}</div>
                        </div>
                        <div>
                          <h5>Artifacts</h5>
                          <ul className="art-list">{(p.artifacts || []).map((a) => <li key={a}>{a}</li>)}</ul>
                        </div>
                        <div>
                          <h5>Tags</h5>
                          <div className="stack-list">{p.tags.map((t) => <span key={t}>{t}</span>)}</div>
                        </div>
                      </div>
                    </div>
                }
                </article>
              )}
            </div>
          </section>

          {/* EXPERIENCE */}
          <section id="experience" className="section">
            <header className="sec-head">
              <div className="num">§ 04</div>
              <div className="title"><span className="ico"><Icon name="activity" /></span><h2>Service Record<span className="sub">2023 → present</span></h2></div>
              <div className="meta">{D.experience.length} roles<button className="share-btn" onClick={() => copySectionLink('experience')} title="Copy link to this section">🔗</button></div>
            </header>
            <div className="tl">
              {D.experience.map((e, i) =>
              <React.Fragment key={i}>
                  <div className="yr-cell">{e.years}</div>
                  <div className="who-cell">
                    <h3 className="who">{e.company}</h3>
                    <div className="role">{e.role}</div>
                  </div>
                  <div className="note-cell">{withAcronyms(e.note)}</div>
                </React.Fragment>
              )}
              {D.education.map((e, i) =>
              <React.Fragment key={'ed' + i}>
                  <div className="yr-cell">{e.years}</div>
                  <div className="who-cell edu">
                    <h3 className="who">{e.school}</h3>
                    <div className="role">Education</div>
                  </div>
                  <div className="note-cell">{withAcronyms(e.degree)}</div>
                </React.Fragment>
              )}
              {(D.volunteering || []).map((v, i) =>
              <React.Fragment key={'vol' + i}>
                  <div className="yr-cell">{v.years}</div>
                  <div className="who-cell edu">
                    <h3 className="who">{v.org}</h3>
                    <div className="role">Volunteer</div>
                  </div>
                  <div className="note-cell">{withAcronyms(v.role)}</div>
                </React.Fragment>
              )}
            </div>
          </section>

          {/* SKILLS */}
          <section id="skills" className="section">
            <header className="sec-head">
              <div className="num">§ 05</div>
              <div className="title"><span className="ico"><Icon name="cpu" /></span><h2>Capabilities<span className="sub">Tools of the trade</span></h2></div>
              <div className="meta">{Object.keys(D.skills).length} domains<button className="share-btn" onClick={() => copySectionLink('skills')} title="Copy link to this section">🔗</button></div>
            </header>
            <div className="skills">
              {Object.entries(D.skills).map(([k, v]) =>
              <div key={k}>
                  <h4><span className="ico"><Icon name="layers" /></span>{k}</h4>
                  <div className="row">{v.map((s) => <span key={s} className="chip">{s}</span>)}</div>
                </div>
              )}
            </div>
          </section>

          {/* WRITING */}
          <section id="writing" className="section">
            <header className="sec-head">
              <div className="num">§ 06</div>
              <div className="title"><span className="ico"><Icon name="notebook" /></span><h2>Field Notes<span className="sub">MY DIGITAL GARDEN</span></h2></div>
              <div className="meta">{D.writing.length} entries<button className="share-btn" onClick={() => copySectionLink('writing')} title="Copy link to this section">🔗</button></div>
            </header>
            <div className="writing">
              {D.writing.map((w, i) => {
                const slug = w.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
                const isExt = !!w.url;
                const href = isExt ? w.url : `Notes/${slug}.html`;
                return (
                  <a
                    key={i}
                    className="write-row"
                    href={href}
                    target={isExt ? '_blank' : undefined}
                    rel={isExt ? 'noopener noreferrer' : undefined}>
                    
                    <div className="date">{w.date}</div>
                    <div className={'kind ' + w.kind}>{w.kind}{w.venue ? ` · ${w.venue}` : ''}</div>
                    <div>
                      <h3 className="ttl">{w.title}</h3>
                      <div className="ex">{w.excerpt}</div>
                    </div>
                    <div className="arr"><Icon name={isExt ? 'external' : 'arrowRight'} /></div>
                  </a>);

              })}
            </div>
          </section>

          {/* NOW */}
          <section id="now" className="section">
            <header className="sec-head">
              <div className="num">§ 07</div>
              <div className="title"><span className="ico"><Icon name="radio" /></span><h2>Now<span className="sub">Live · {D.now.location} · {CURRENT_MONTH_TITLE}</span></h2></div>
              <div className="meta">Auto-updated<button className="share-btn" onClick={() => copySectionLink('now')} title="Copy link to this section">🔗</button></div>
            </header>
            <div className="now-card">
              <div className="now-bar">
                <span className="live"><span className="live-dot"></span>CURRENT FOCUS</span>
                <span className="ts">{liveTime} ET</span>
              </div>
              <div className="now-body">
                <div className="row"><span className="k">building</span><span className="v">{withAcronyms(D.now.building)}</span></div>
                <div className="row"><span className="k">reading</span><span className="v">{withAcronyms(D.now.reading)}</span></div>
                <div className="row"><span className="k">learning</span><span className="v">{withAcronyms(D.now.learning)}</span></div>
              </div>
            </div>
          </section>

          {/* CONTACT */}
          <section id="contact" className="section" style={{ borderBottom: 'none' }}>
            <header className="sec-head">
              <div className="num">§ 08</div>
              <div className="title"><span className="ico"><Icon name="mail" /></span><h2>Comms<span className="sub">Open a channel</span></h2></div>
              <div className="meta"><button className="share-btn" onClick={() => copySectionLink('contact')} title="Copy link to this section">🔗</button></div>
            </header>
            <div className="contact-block">
              <p className="pull">Mission-critical Navy systems. <span className="ac">{withAcronyms("SysML architecture artifacts that hold up under certification review.")}</span></p>
              <div className="links">
                <a href={`mailto:${D.contact.email}`} title={`Click to compose · Right-click then "Copy link"`} onClick={(e) => {e.preventDefault();copyToClipboard(D.contact.email, 'Email');setTimeout(() => {window.location.href = `mailto:${D.contact.email}`;}, 100);}}>
                  <div className="head"><span className="k">EMAIL</span><span className="ico"><Icon name="mail" /></span></div>
                  <span className="v">{D.contact.email}</span>
                </a>
                <a href={`tel:${D.contact.phone}`} title="Click to call · Auto-copies to clipboard" onClick={(e) => {e.preventDefault();copyToClipboard(D.contact.phone, 'Phone');}}>
                  <div className="head"><span className="k">PHONE</span><span className="ico"><Icon name="radio" /></span></div>
                  <span className="v">{D.contact.phone}</span>
                </a>
                <a href={`https://${D.contact.linkedin}`} title="Click to open LinkedIn" target="_blank" rel="noopener noreferrer">
                  <div className="head"><span className="k">LINKEDIN</span><span className="ico"><Icon name="external" /></span></div>
                  <span className="v">{D.contact.linkedin}</span>
                </a>
                <a href="Resume.html" title="Open Resume">
                  <div className="head"><span className="k">RESUME</span><span className="ico"><Icon name="download" /></span></div>
                  <span className="v">Resume</span>
                </a>
              </div>
            </div>
          </section>

          <div className="colophon">
            <span>END OF DOCUMENT · MATTHEW BUNN · {CURRENT_MONTH_UPPER}</span>
            <span>matthew@matthew-b.com</span>
          </div>
        </main>
      </div>
      <CommandPalette open={cmdOpen} setOpen={setCmdOpen} />
    </div>);

}

window.DossierV2 = DossierV2;