// fs-ui.jsx — shared UI for ShortsFieldStation.org
// Depends on window.FS_SEALS (fs-seals.js) and the FS_* data globals.

const { useState, useEffect } = React;

/* ---- seals: render the real artwork via dangerouslySetInnerHTML ---- */
function Seal({ dept, size=120, house=false, className, style, title }){
  let markup;
  if(house) markup = FS_SEALS.houseSealR4(size, 'var(--ink)');
  else {
    const opts = dept.legendOverride ? { legend: dept.s1 } : {};
    markup = FS_SEALS.sealRound4(dept.key, dept.s1, dept.s2, dept.code, dept.plate, dept.color, size, opts);
  }
  return <div className={className} style={style} title={title} aria-label={title}
    dangerouslySetInnerHTML={{__html:markup}}/>;
}
const DEPT_BY = {}; FS_SEALS.DEPTS.forEach(d=>{ DEPT_BY[d.key]=d; });

/* ---- live clock (unit local time, ticks) ---- */
function useClock(){
  const [t,setT] = useState(()=>fmtClock());
  useEffect(()=>{ const id=setInterval(()=>setT(fmtClock()), 15000); return ()=>clearInterval(id); },[]);
  return t;
}
function fmtClock(){ const d=new Date(); return String(d.getHours()).padStart(2,'0')+':'+String(d.getMinutes()).padStart(2,'0'); }

/* ---- masthead ---- */
function Masthead({ route, go, session, onSignIn }){
  const [open,setOpen] = useState(false);
  const nav = ()=> setOpen(false);
  return (
    <header className="mast">
      <div className="mast-in">
        <div className="brand" onClick={()=>{go('home');nav();}}>
          <div className="wm">
            <div className="n">Short&rsquo;s Resort Field Station</div>
            <div className="s">SRFS · Est. 2026 · Texas Hill Country</div>
          </div>
        </div>
        <button className="burger" onClick={()=>setOpen(o=>!o)} aria-label="Menu"><span></span><span></span><span></span></button>
        <nav className={'nav'+(open?' open':'')}>
          {FS_SECTIONS.map(s=>(
            <a key={s.id} className={route===s.id?'on':''} onClick={()=>{go(s.id);nav();}}>
              <span className="num">{s.no}</span>{s.title}
            </a>
          ))}
        </nav>
      </div>
    </header>
  );
}

/* ---- folio header on each sheet ---- */
function Folio({ left, right }){
  return <div className="folio"><span>{left}</span><span>{right}</span></div>;
}
function SectionHead({ no, title, deck, aside }){
  return (
    <div style={{marginBottom:'8px'}}>
      <div className="shead">
        <div>
          <div className="eyebrow">Section {no} · Short&rsquo;s Resort Field Station</div>
          <h1 className="disp">{title}</h1>
        </div>
        {aside}
      </div>
      {deck && <p className="deck">{deck}</p>}
    </div>
  );
}

/* ---- the property plat (real trace from the section atlas) ---- */
function PlatMap(){
  return (
    <svg className="map" viewBox="0 0 760 805" xmlns="http://www.w3.org/2000/svg" fontFamily="JetBrains Mono, monospace">
      <g stroke="#1B1813" strokeWidth="1.2" strokeLinejoin="round" fillOpacity="0.55">
        <polygon points="131,4 300,130 220,300 72,214" fill="#8E9B85"/>
        <polygon points="72,214 220,300 250,500 290,760 226,724 150,520 40,300" fill="#5C7A78"/>
        <polygon points="220,300 300,130 415,148 345,788 290,760 250,500" fill="#5C7A78"/>
        <polygon points="415,148 515,195 398,800 345,788" fill="#5C7A78"/>
        <polygon points="515,195 610,242 450,802 398,800" fill="#B58A3C"/>
        <polygon points="610,242 700,283 470,801 450,802" fill="#B58A3C"/>
        <polygon points="700,283 755,309 628,472 470,801" fill="#8E9B85"/>
      </g>
      <path d="M62,206 L40,300 L150,520 L210,690 L232,732" fill="none" stroke="#5C7A78" strokeWidth="9" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M62,206 L40,300 L150,520 L210,690 L232,732" fill="none" stroke="#1B1813" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round"/>
      <polygon points="131,4 326,102 755,309 628,472 470,801 226,724 150,520 40,300 72,214 140,250 176,198" fill="none" stroke="#1B1813" strokeWidth="2.6" strokeLinejoin="round"/>
      <path d="M755,309 L628,472 L470,801" fill="none" stroke="#1B1813" strokeWidth="1" strokeDasharray="2 5" strokeLinejoin="round"/>
      <rect x="556" y="498" width="15" height="15" fill="#1B1813"/>
      <circle cx="165" cy="470" r="6" fill="#5C7A78" stroke="#1B1813" strokeWidth="1.2"/>
      <circle cx="430" cy="640" r="6" fill="#5C7A78" stroke="#1B1813" strokeWidth="1.2"/>
      <g fill="#1B1813" fontSize="11" fontWeight="700" letterSpacing="1">
        <text x="78" y="300">G·01</text><text x="664" y="330">G·02</text><text x="360" y="770">G·03</text>
      </g>
      <g fill="#1B1813" fontFamily="Zilla Slab, serif" fontWeight="900" fontSize="30" textAnchor="middle" style={{paintOrder:'stroke'}} stroke="#F4ECD8" strokeWidth="3.5">
        <text x="178" y="158">4</text><text x="140" y="430">1</text><text x="305" y="430">5</text>
        <text x="428" y="470">3</text><text x="528" y="495">7</text><text x="582" y="540">6</text><text x="648" y="412">2</text>
      </g>
    </svg>
  );
}

/* ---- sign-in modal (operator door; read-only fallback is the default site) ---- */
function SignIn({ onClose, onSignIn }){
  const [u,setU] = useState('');
  const [p,setP] = useState('');
  const [err,setErr] = useState(false);
  const submit = ()=>{
    // demo creds; real auth handled by the unit backend later
    if(u.trim() && (p==='steward' || p==='2468')) onSignIn({ name:'Operator', role:'Steward' });
    else if(u.trim() && (p==='grower' || p==='1357')) onSignIn({ name:'Operator', role:'Grower' });
    else setErr(true);
  };
  return (
    <div className="mback" onClick={onClose}>
      <div className="modal" onClick={e=>e.stopPropagation()}>
        <div className="mh"><span className="t">Operator Sign-In</span><span className="x" onClick={onClose}>&times;</span></div>
        <div className="mb">
          <p style={{fontFamily:'Newsreader',fontStyle:'italic',fontSize:'15px',color:'var(--char)',marginBottom:'18px',lineHeight:1.5}}>
            Control of the live Propagation Unit is restricted to station operators. Everyone else is welcome to look around in observation mode.
          </p>
          <div className="k">Operator</div>
          <input className="field" value={u} onChange={e=>{setU(e.target.value);setErr(false);}} placeholder="callsign"/>
          <div className="k">Passphrase</div>
          <input className="field" type="password" value={p} onChange={e=>{setP(e.target.value);setErr(false);}} placeholder="••••••"
            onKeyDown={e=>e.key==='Enter'&&submit()}/>
          {err && <div className="warn">Not recognized — try passphrase “steward” for the demo</div>}
        </div>
        <div className="mf-foot">
          <span className="n">No account? You already have the read-only tour.</span>
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn solid" onClick={submit}>Sign In</button>
        </div>
      </div>
    </div>
  );
}

/* ---- footer ---- */
/* ---- agency partner marks (monochrome lockups; drop in official art later) ---- */
function AgencyMark({ kind, size=46 }){
  if(kind==='nrcs') return (
    <svg width={size} height={size} viewBox="0 0 100 100" role="img" aria-label="USDA NRCS" style={{color:'var(--ink)',flex:'none'}}>
      <circle cx="50" cy="50" r="46" fill="none" stroke="currentColor" strokeWidth="2.5"/>
      <circle cx="50" cy="50" r="40" fill="none" stroke="currentColor" strokeWidth="0.8"/>
      <path d="M16 64 Q50 50 84 64" fill="none" stroke="currentColor" strokeWidth="2"/>
      <path d="M20 72 Q50 60 80 72" fill="none" stroke="currentColor" strokeWidth="2"/>
      <path d="M50 56 C59 42 59 30 50 20 C41 30 41 42 50 56 Z" fill="currentColor"/>
      <line x1="50" y1="54" x2="50" y2="34" stroke="var(--bone)" strokeWidth="1.4"/>
    </svg>
  );
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" role="img" aria-label="Texas Parks and Wildlife" style={{color:'var(--ink)',flex:'none'}}>
      <path d="M20 22 L57 22 L57 31 L69 31 L74 39 L83 41 L79 53 L70 61 L66 80 L54 75 L47 83 L39 74 L29 74 L27 57 L19 49 L24 39 L20 22 Z" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinejoin="round"/>
      <circle cx="45" cy="47" r="3.4" fill="currentColor"/>
    </svg>
  );
}

function Footer({ go, session, onSignIn, onSignOut }){
  return (
    <footer className="foot">
      <div className="foot-in">
        <div className="seal-row">
          {FS_SEALS.DEPTS.map(d=>(
            <Seal key={d.key} dept={d} size={108} className="s" title={d.nm}/>
          ))}
        </div>
        <div className="foot-cols">
          <div>
            <h5>About this site</h5>
            <p className="colophon">
              Short&rsquo;s Resort Field Station (SRFS) is the public record of an ongoing land restoration in the Texas Hill Country, above the Lampasas River.
              We&rsquo;re rebuilding oak savanna, prairie and riparian habitat one season at a time &mdash; and posting the whole thing in the open. The documents and code here are free to borrow.
            </p>
            <div style={{display:'flex',gap:'18px',marginTop:'20px',flexWrap:'wrap'}}>
              {FS_FUNDERS.map(f=>(
                <a key={f.k} href={f.url} target="_blank" rel="noopener" title={f.program} style={{display:'flex',alignItems:'center',gap:'10px',color:'var(--ink)'}}>
                  <AgencyMark kind={f.mark} size={38}/>
                  <span className="mono" style={{fontSize:'10px',letterSpacing:'0.1em',textTransform:'uppercase',lineHeight:1.4}}>{f.k}<br/><span style={{opacity:.65}}>{f.short} ↗</span></span>
                </a>
              ))}
            </div>
          </div>
          <div>
            <h5>Sections</h5>
            <ul>
              {FS_SECTIONS.map(s=><li key={s.id}><a onClick={()=>go(s.id)}>{s.no} · {s.title}</a></li>)}
            </ul>
          </div>
          <div>
            <h5>Station</h5>
            <ul>
              <li><a href={'https://'+FS_REPO.path} target="_blank" rel="noopener">Source repository ↗</a></li>
              <li><a onClick={()=>go('ii')}>The Propagation Unit</a></li>
              {session
                ? <li><a onClick={onSignOut}>Sign out · {session.role}</a></li>
                : <li><a onClick={onSignIn}>Operator sign-in</a></li>}
              <li><a onClick={()=>go('support')}>Get involved</a></li>
            </ul>
          </div>
        </div>
        <div className="foot-base">
          <span>Supported by <a href={FS_FUNDERS[0].url} target="_blank" rel="noopener">USDA–NRCS · EQIP</a> &middot; <a href={FS_FUNDERS[1].url} target="_blank" rel="noopener">Texas Parks &amp; Wildlife · Pastures for Upland Birds</a></span>
          <span>ShortsFieldStation.org &middot; No. 01 &middot; MMXXVI</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Seal, DEPT_BY, useClock, fmtClock, Masthead, Folio, SectionHead, PlatMap, AgencyMark, SignIn, Footer });
