// BVI Timeline — Reference Data Editor Component
// Handles editing of Monarchs, Wars, VI Governors, LI Governors, VI Status
// Exported to window for use in Timeline.html

const { useState, useMemo } = React;

// ── SHARED UTILITIES ──────────────────────────────────────────────────────────
const iS  = { padding:'4px 6px', fontSize:12, border:'1px solid #d4c8b8', borderRadius:4, background:'#fdf9f4', width:'100%' };
const thS = { padding:'7px 10px', fontSize:11, fontWeight:700, letterSpacing:'0.05em', textTransform:'uppercase', color:'#7a6a55', borderBottom:'2px solid #d4c8b8', textAlign:'left', whiteSpace:'nowrap' };
const tdS = { padding:'5px 6px', borderBottom:'1px solid #ede8e0', verticalAlign:'middle' };
const labelS = { fontSize:10, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'#7a6a55', marginBottom:4, display:'block' };

function ActBtn({ label, onClick, danger }) {
  return (
    <button onClick={onClick} style={{padding:'2px 7px',fontSize:11,border:`1px solid ${danger?'#e8b4b4':'#d4c8b8'}`,borderRadius:3,background:'#fff',color:danger?'#8b1a1a':'#444',cursor:'pointer'}}>
      {label}
    </button>
  );
}

function VerifiedBadge({ verified }) {
  return verified
    ? <span style={{color:'#2e7d32',fontSize:13}}>✓</span>
    : <span style={{color:'#b45309',fontSize:13}}>⚠</span>;
}

// Shared source/citation/notes/verified expandable panel
function SourcePanel({ item, onUpdate }) {
  return (
    <tr>
      <td colSpan={20} style={{background:'#f0ebe3',padding:'10px 16px 14px 44px',borderBottom:'2px solid #d4c8b8'}}>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,maxWidth:720}}>
          <div>
            <label style={labelS}>Source</label>
            <input style={iS} value={item.source||''} onChange={e=>onUpdate('source',e.target.value)} placeholder="e.g. Oxford DNB, Letters Patent…"/>
          </div>
          <div>
            <label style={labelS}>Citation / Reference</label>
            <input style={iS} value={item.citation||''} onChange={e=>onUpdate('citation',e.target.value)} placeholder="e.g. TNA ref., statute, ISBN…"/>
          </div>
          <div style={{gridColumn:'1/-1'}}>
            <label style={labelS}>Research Notes</label>
            <textarea style={{...iS,height:52,resize:'vertical',fontFamily:'inherit'}} value={item.notes||''} onChange={e=>onUpdate('notes',e.target.value)} placeholder="Queries, cross-references, rabbit holes…"/>
          </div>
          <div style={{gridColumn:'1/-1'}}>
            <label style={{display:'flex',alignItems:'center',gap:8,cursor:'pointer',fontSize:12,color:'#3a2e1e'}}>
              <input type="checkbox" checked={!!item.verified} onChange={e=>onUpdate('verified',e.target.checked)} style={{width:15,height:15,accentColor:'#2e7d32'}}/>
              <span>Verified against primary source</span>
              {item.verified ? <span style={{color:'#2e7d32',fontSize:11,fontWeight:600}}>✓ Verified</span> : <span style={{color:'#b45309',fontSize:11}}>⚠ Unverified</span>}
            </label>
          </div>
        </div>
      </td>
    </tr>
  );
}

// Date input group — year/month/day + calendar toggle
function DateInput({ label, year, month, day, cal, onChange }) {
  return (
    <div>
      <label style={labelS}>{label}</label>
      <div style={{display:'flex',gap:4,alignItems:'center',flexWrap:'wrap'}}>
        <input type="number" placeholder="Year" value={year||''} onChange={e=>onChange('year',e.target.value)}
          style={{...iS,width:68,padding:'3px 5px'}}/>
        <input type="number" placeholder="Mo" min={1} max={12} value={month||''} onChange={e=>onChange('month',e.target.value)}
          style={{...iS,width:46,padding:'3px 5px'}}/>
        <input type="number" placeholder="Day" min={1} max={31} value={day||''} onChange={e=>onChange('day',e.target.value)}
          style={{...iS,width:46,padding:'3px 5px'}}/>
        <select value={cal||'greg'} onChange={e=>onChange('cal',e.target.value)}
          style={{...iS,width:100,padding:'3px 5px',fontSize:11}}>
          <option value="greg">Gregorian</option>
          <option value="julian">Julian (O.S.)</option>
        </select>
      </div>
    </div>
  );
}

// ── MONARCH EDITOR ────────────────────────────────────────────────────────────
function MonarchEditor({ monarchs, setMonarchs, people }) {
  const [exp, setExp] = useState(null);

  function upd(i, f, v) {
    setMonarchs(p => p.map((m,j) => j!==i ? m : {...m, [f]: ['sYear','eYear','sMonth','eMonth','sDay','eDay'].includes(f) ? (parseInt(v)||undefined) : v}));
  }
  function updDate(i, prefix, field, val) {
    upd(i, prefix+field.charAt(0).toUpperCase()+field.slice(1), val);
  }
  function addM() {
    const l = monarchs[monarchs.length-1];
    setMonarchs(p => [...p, {name:'New Monarch', sCal:'greg', sYear:l?l.eYear:1500, sMonth:1, sDay:1, eCal:'greg', eYear:l?l.eYear+20:1520, eMonth:1, eDay:1, c:'#8b1a1a', source:'', citation:'', verified:false, notes:''}]);
    setExp(monarchs.length);
  }
  function delM(i) { if(confirm('Delete?')) { setMonarchs(p=>p.filter((_,j)=>j!==i)); setExp(null); } }
  function movM(i,d) { setMonarchs(p=>{ const a=[...p],j=i+d; if(j<0||j>=a.length) return a; [a[i],a[j]]=[a[j],a[i]]; return a; }); }

  function jdnFor(m, prefix) {
    const y = m[prefix+'Year'], mo = m[prefix+'Month']||1, d = m[prefix+'Day']||1;
    if (!y) return null;
    return m[prefix+'Cal']==='julian' ? TU.julianToJDN(y,mo,d) : TU.gregorianToJDN(y,mo,d);
  }

  return (
    <>
      <div style={{display:'flex',gap:8,marginBottom:10}}>
        <button onClick={addM} style={{padding:'5px 14px',fontSize:12,border:'none',borderRadius:4,background:'#8b1a1a',color:'#fff',cursor:'pointer'}}>+ Add Monarch</button>
        <button onClick={()=>{ if(confirm('Reset to original seed data?')) { setMonarchs(UK_MONARCHS); setExp(null); } }}
          style={{padding:'5px 14px',fontSize:12,border:'1px solid #c4b49a',borderRadius:4,background:'#fff',color:'#7a5a20',cursor:'pointer'}}>Reset to defaults</button>
      </div>
      <div style={{overflowX:'auto',overflowY:'auto',maxHeight:'calc(100vh - 240px)'}}>
        <table style={{width:'100%',borderCollapse:'collapse',minWidth:700}}>
          <thead style={{position:'sticky',top:0,background:'#f5f0e8',zIndex:2}}>
            <tr>
              <th style={{...thS,width:28}}></th>
              <th style={thS}>Name</th>
              <th style={thS}>Accession date</th>
              <th style={thS}>End date</th>
              <th style={thS}>Colour</th>
              <th style={thS}>Person</th>
              <th style={thS}>Source</th>
              <th style={{...thS,width:28}}>V</th>
              <th style={thS}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {monarchs.map((m,i) => {
              const isExp = exp===i;
              const sJDN = jdnFor(m,'s'), eJDN = jdnFor(m,'e');
              const sDisp = sJDN ? TU.jdnToDisplay(sJDN) : `${m.sYear||'?'}`;
              const eDisp = eJDN ? TU.jdnToDisplay(eJDN) : `${m.eYear||'?'}`;
              return (
                <React.Fragment key={i}>
                  <tr style={{background:isExp?'#f0ebe3':i%2===0?'#fff':'#faf7f3',cursor:'pointer'}} onClick={()=>setExp(isExp?null:i)}>
                    <td style={{...tdS,textAlign:'center',fontSize:11,color:'#c4a87a',userSelect:'none'}}>{isExp?'▼':'▶'}</td>
                    <td style={{...tdS,minWidth:160}}>
                      <input style={iS} value={m.name} onClick={e=>e.stopPropagation()} onChange={e=>{e.stopPropagation();upd(i,'name',e.target.value)}}/>
                    </td>
                    <td style={{...tdS,minWidth:220}} onClick={e=>e.stopPropagation()}>
                      <DateInput label="" year={m.sYear} month={m.sMonth} day={m.sDay} cal={m.sCal||'greg'}
                        onChange={(f,v)=>updDate(i,'s',f,v)}/>
                      <div style={{fontSize:9,color:'#8a7a68',marginTop:2}}>{sDisp}</div>
                    </td>
                    <td style={{...tdS,minWidth:220}} onClick={e=>e.stopPropagation()}>
                      <DateInput label="" year={m.eYear} month={m.eMonth} day={m.eDay} cal={m.eCal||'greg'}
                        onChange={(f,v)=>updDate(i,'e',f,v)}/>
                      <div style={{fontSize:9,color:'#8a7a68',marginTop:2}}>{eDisp}</div>
                    </td>
                    <td style={{...tdS,width:80}} onClick={e=>e.stopPropagation()}>
                      <div style={{display:'flex',alignItems:'center',gap:4}}>
                        <input type="color" value={m.c||'#888'} onChange={e=>upd(i,'c',e.target.value)} style={{width:26,height:20,border:'none',cursor:'pointer',padding:0,borderRadius:2}}/>
                        <span style={{fontSize:9,fontFamily:'monospace',color:'#7a6a55'}}>{m.c}</span>
                      </div>
                    </td>
                    <td style={{...tdS,minWidth:140}} onClick={e=>e.stopPropagation()}>
                      <PersonLink value={m.personId} onChange={v=>upd(i,'personId',v)} people={people||[]}/>
                    </td>
                    <td style={{...tdS,fontSize:11,color:'#6b5a45',maxWidth:160}} onClick={e=>e.stopPropagation()}>
                      <span style={{opacity:0.7}}>{m.source ? m.source.slice(0,35)+(m.source.length>35?'…':'') : <em style={{color:'#ccc'}}>no source</em>}</span>
                    </td>
                    <td style={{...tdS,textAlign:'center'}} onClick={e=>e.stopPropagation()}><VerifiedBadge verified={m.verified}/></td>
                    <td style={{...tdS,width:220}} onClick={e=>e.stopPropagation()}>
                      <div style={{display:'flex',gap:4}}>
                        <ActBtn label="Move up" onClick={()=>movM(i,-1)}/><ActBtn label="Move down" onClick={()=>movM(i,1)}/><ActBtn label="Delete" onClick={()=>delM(i)} danger/>
                      </div>
                    </td>
                  </tr>
                  {isExp && <SourcePanel item={m} onUpdate={(f,v)=>upd(i,f,v)}/>}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>
      <div style={{marginTop:8,fontSize:11,color:'#a09080'}}>End date = first day of next reign. Pre-1752 English dates are Julian (O.S.).</div>
    </>
  );
}

// ── WARS EDITOR ───────────────────────────────────────────────────────────────
function WarsEditor({ wars, setWars }) {
  const [exp, setExp] = useState(null);

  function upd(i,f,v) { setWars(p=>p.map((w,j)=>j!==i?w:{...w,[f]:['startYear','endYear'].includes(f)?parseInt(v)||w[f]:v})); }
  function addW() { const l=wars[wars.length-1]; setWars(p=>[...p,{id:'u_w_'+Date.now(),name:'New War',startYear:l?l.endYear:1600,endYear:l?l.endYear+10:1610,type:'BOTH',color:'#8b2a00',source:'',citation:'',verified:false,notes:''}]); setExp(wars.length); }
  function delW(i) { if(confirm('Delete?')) { setWars(p=>p.filter((_,j)=>j!==i)); setExp(null); } }
  function movW(i,d) { setWars(p=>{ const a=[...p],j=i+d; if(j<0||j>=a.length) return a; [a[i],a[j]]=[a[j],a[i]]; return a; }); }

  return (
    <>
      <div style={{display:'flex',gap:8,marginBottom:10}}>
        <button onClick={addW} style={{padding:'5px 14px',fontSize:12,border:'none',borderRadius:4,background:'#8b1a1a',color:'#fff',cursor:'pointer'}}>+ Add War</button>
        <button onClick={()=>{ if(confirm('Reset wars to original seed data?')) { setWars(WARS); setExp(null); } }}
          style={{padding:'5px 14px',fontSize:12,border:'1px solid #c4b49a',borderRadius:4,background:'#fff',color:'#7a5a20',cursor:'pointer'}}>Reset to defaults</button>
      </div>
      <div style={{overflowX:'auto',overflowY:'auto',maxHeight:'calc(100vh - 240px)'}}>
        <table style={{width:'100%',borderCollapse:'collapse',minWidth:700}}>
          <thead style={{position:'sticky',top:0,background:'#f5f0e8',zIndex:2}}>
            <tr>
              <th style={{...thS,width:28}}></th>
              <th style={thS}>Name</th>
              <th style={thS}>Start</th>
              <th style={thS}>End</th>
              <th style={thS}>Type</th>
              <th style={thS}>Colour</th>
              <th style={thS}>Source</th>
              <th style={{...thS,width:28}}>V</th>
              <th style={thS}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {wars.map((w,i) => {
              const isExp = exp===i;
              return (
                <React.Fragment key={i}>
                  <tr style={{background:isExp?'#f0ebe3':i%2===0?'#fff':'#faf7f3',cursor:'pointer'}} onClick={()=>setExp(isExp?null:i)}>
                    <td style={{...tdS,textAlign:'center',fontSize:11,color:'#c4a87a',userSelect:'none'}}>{isExp?'▼':'▶'}</td>
                    <td style={{...tdS,minWidth:200}}><input style={iS} value={w.name} onClick={e=>e.stopPropagation()} onChange={e=>{e.stopPropagation();upd(i,'name',e.target.value)}}/></td>
                    <td style={{...tdS,width:90}}><input style={iS} type="number" value={w.startYear} onClick={e=>e.stopPropagation()} onChange={e=>{e.stopPropagation();upd(i,'startYear',e.target.value)}}/></td>
                    <td style={{...tdS,width:90}}><input style={iS} type="number" value={w.endYear}   onClick={e=>e.stopPropagation()} onChange={e=>{e.stopPropagation();upd(i,'endYear',e.target.value)}}/></td>
                    <td style={{...tdS,width:90}} onClick={e=>e.stopPropagation()}>
                      <select style={iS} value={w.type} onChange={e=>upd(i,'type',e.target.value)}>
                        <option value="EUR">European</option>
                        <option value="CAR">Caribbean</option>
                        <option value="BOTH">Both</option>
                      </select>
                    </td>
                    <td style={{...tdS,width:80}} onClick={e=>e.stopPropagation()}>
                      <div style={{display:'flex',alignItems:'center',gap:4}}>
                        <input type="color" value={w.color||'#8b2a00'} onChange={e=>upd(i,'color',e.target.value)} style={{width:26,height:20,border:'none',cursor:'pointer',padding:0,borderRadius:2}}/>
                        <span style={{fontSize:9,fontFamily:'monospace',color:'#7a6a55'}}>{w.color}</span>
                      </div>
                    </td>
                    <td style={{...tdS,fontSize:11,color:'#6b5a45',maxWidth:140}} onClick={e=>e.stopPropagation()}>
                      <span style={{opacity:0.7}}>{w.source ? w.source.slice(0,30)+(w.source.length>30?'…':'') : <em style={{color:'#ccc'}}>no source</em>}</span>
                    </td>
                    <td style={{...tdS,textAlign:'center'}} onClick={e=>e.stopPropagation()}><VerifiedBadge verified={w.verified}/></td>
                    <td style={{...tdS,width:220}} onClick={e=>e.stopPropagation()}>
                      <div style={{display:'flex',gap:4}}>
                        <ActBtn label="Move up" onClick={()=>movW(i,-1)}/><ActBtn label="Move down" onClick={()=>movW(i,1)}/><ActBtn label="Delete" onClick={()=>delW(i)} danger/>
                      </div>
                    </td>
                  </tr>
                  {isExp && <SourcePanel item={w} onUpdate={(f,v)=>upd(i,f,v)}/>}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ── GOVERNOR EDITOR (reusable for VI and LI) ──────────────────────────────────
function GovernorEditor({ govs, setGovs, defaultData, label, people }) {
  const [exp, setExp] = useState(null);

  function upd(i,f,v) {
    const numF = ['startYear','startMonth','startDay','endYear','endMonth','endDay'];
    setGovs(p=>p.map((g,j)=>j!==i?g:{...g,[f]:numF.includes(f)?parseInt(v)||undefined:v}));
  }
  function add() {
    const l = govs[govs.length-1];
    setGovs(p=>[...p,{id:'u_g_'+Date.now(),name:'New Entry',title:'',startYear:l?l.endYear:1600,startMonth:1,startDay:1,endYear:l?l.endYear+10:1610,endMonth:1,endDay:1,source:'',citation:'',verified:false,notes:''}]);
    setExp(govs.length);
  }
  function del(i) { if(confirm('Delete?')) { setGovs(p=>p.filter((_,j)=>j!==i)); setExp(null); } }
  function mov(i,d) { setGovs(p=>{ const a=[...p],j=i+d; if(j<0||j>=a.length) return a; [a[i],a[j]]=[a[j],a[i]]; return a; }); }

  function dispDate(y,m,d) { if(!y) return '?'; return `${d?d+' ':''}${m?TU.MONTHS_SHORT[m-1]+' ':''}${y}`; }

  return (
    <>
      <div style={{display:'flex',gap:8,marginBottom:10}}>
        <button onClick={add} style={{padding:'5px 14px',fontSize:12,border:'none',borderRadius:4,background:'#8b1a1a',color:'#fff',cursor:'pointer'}}>+ Add Entry</button>
        <button onClick={()=>{ if(confirm(`Reset ${label} to original seed data?`)) { setGovs(defaultData); setExp(null); } }}
          style={{padding:'5px 14px',fontSize:12,border:'1px solid #c4b49a',borderRadius:4,background:'#fff',color:'#7a5a20',cursor:'pointer'}}>Reset to defaults</button>
      </div>
      <div style={{overflowX:'auto',overflowY:'auto',maxHeight:'calc(100vh - 240px)'}}>
        <table style={{width:'100%',borderCollapse:'collapse',minWidth:700}}>
          <thead style={{position:'sticky',top:0,background:'#f5f0e8',zIndex:2}}>
            <tr>
              <th style={{...thS,width:28}}></th>
              <th style={thS}>Name</th>
              <th style={thS}>Title</th>
              <th style={thS}>Start</th>
              <th style={thS}>End</th>
              <th style={thS}>Person</th>
              <th style={thS}>Source</th>
              <th style={{...thS,width:28}}>V</th>
              <th style={thS}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {govs.map((g,i) => {
              const isExp = exp===i;
              return (
                <React.Fragment key={i}>
                  <tr style={{background:isExp?'#f0ebe3':i%2===0?'#fff':'#faf7f3',cursor:'pointer'}} onClick={()=>setExp(isExp?null:i)}>
                    <td style={{...tdS,textAlign:'center',fontSize:11,color:'#c4a87a',userSelect:'none'}}>{isExp?'▼':'▶'}</td>
                    <td style={{...tdS,minWidth:160}}><input style={iS} value={g.name} onClick={e=>e.stopPropagation()} onChange={e=>{e.stopPropagation();upd(i,'name',e.target.value)}}/></td>
                    <td style={{...tdS,minWidth:130}}><input style={iS} value={g.title||''} onClick={e=>e.stopPropagation()} onChange={e=>{e.stopPropagation();upd(i,'title',e.target.value)}}/></td>
                    <td style={{...tdS,minWidth:160}} onClick={e=>e.stopPropagation()}>
                      <div style={{display:'grid',gridTemplateColumns:'56px 40px 40px',gap:3}}>
                        <input type="number" placeholder="Year" value={g.startYear||''} onChange={e=>upd(i,'startYear',e.target.value)} style={{...iS,padding:'2px 4px'}}/>
                        <input type="number" placeholder="Mo"   value={g.startMonth||''} onChange={e=>upd(i,'startMonth',e.target.value)} style={{...iS,padding:'2px 4px'}}/>
                        <input type="number" placeholder="D"    value={g.startDay||''} onChange={e=>upd(i,'startDay',e.target.value)} style={{...iS,padding:'2px 4px'}}/>
                      </div>
                      <div style={{fontSize:9,color:'#8a7a68',marginTop:2}}>{dispDate(g.startYear,g.startMonth,g.startDay)}</div>
                    </td>
                    <td style={{...tdS,minWidth:160}} onClick={e=>e.stopPropagation()}>
                      <div style={{display:'grid',gridTemplateColumns:'56px 40px 40px',gap:3}}>
                        <input type="number" placeholder="Year" value={g.endYear||''} onChange={e=>upd(i,'endYear',e.target.value)} style={{...iS,padding:'2px 4px'}}/>
                        <input type="number" placeholder="Mo"   value={g.endMonth||''} onChange={e=>upd(i,'endMonth',e.target.value)} style={{...iS,padding:'2px 4px'}}/>
                        <input type="number" placeholder="D"    value={g.endDay||''} onChange={e=>upd(i,'endDay',e.target.value)} style={{...iS,padding:'2px 4px'}}/>
                      </div>
                      <div style={{fontSize:9,color:'#8a7a68',marginTop:2}}>{dispDate(g.endYear,g.endMonth,g.endDay)}</div>
                    </td>
                    <td style={{...tdS,minWidth:140}} onClick={e=>e.stopPropagation()}>
                      <PersonLink value={g.personId} onChange={v=>upd(i,'personId',v)} people={people||[]}/>
                    </td>
                    <td style={{...tdS,fontSize:11,color:'#6b5a45',maxWidth:160}} onClick={e=>e.stopPropagation()}>
                      <span style={{opacity:0.7}}>{g.source ? g.source.slice(0,30)+(g.source.length>30?'…':'') : <em style={{color:'#ccc'}}>no source</em>}</span>
                    </td>
                    <td style={{...tdS,textAlign:'center'}} onClick={e=>e.stopPropagation()}><VerifiedBadge verified={g.verified}/></td>
                    <td style={{...tdS,width:220}} onClick={e=>e.stopPropagation()}>
                      <div style={{display:'flex',gap:4}}>
                        <ActBtn label="Move up" onClick={()=>mov(i,-1)}/><ActBtn label="Move down" onClick={()=>mov(i,1)}/><ActBtn label="Delete" onClick={()=>del(i)} danger/>
                      </div>
                    </td>
                  </tr>
                  {isExp && <SourcePanel item={g} onUpdate={(f,v)=>upd(i,f,v)}/>}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ── VI STATUS EDITOR ──────────────────────────────────────────────────────────
function VIStatusEditor({ viStatus, setViStatus }) {
  const [exp, setExp] = useState(null);

  function upd(i,f,v) { setViStatus(p=>p.map((x,j)=>j!==i?x:{...x,[f]:['startYear','endYear'].includes(f)?parseInt(v)||x[f]:v})); }
  function add() { const l=viStatus[viStatus.length-1]; setViStatus(p=>[...p,{startYear:l?l.endYear:1500,endYear:l?l.endYear+50:1550,holder:'GBR',label:'New period',color:'#8b1a1a',source:'',citation:'',verified:false,notes:''}]); setExp(viStatus.length); }
  function del(i) { if(confirm('Delete?')) { setViStatus(p=>p.filter((_,j)=>j!==i)); setExp(null); } }
  function mov(i,d) { setViStatus(p=>{ const a=[...p],j=i+d; if(j<0||j>=a.length) return a; [a[i],a[j]]=[a[j],a[i]]; return a; }); }

  return (
    <>
      <div style={{display:'flex',gap:8,marginBottom:10}}>
        <button onClick={add} style={{padding:'5px 14px',fontSize:12,border:'none',borderRadius:4,background:'#8b1a1a',color:'#fff',cursor:'pointer'}}>+ Add Period</button>
        <button onClick={()=>{ if(confirm('Reset to original seed data?')) { setViStatus(VI_STATUS_PERIODS); setExp(null); } }}
          style={{padding:'5px 14px',fontSize:12,border:'1px solid #c4b49a',borderRadius:4,background:'#fff',color:'#7a5a20',cursor:'pointer'}}>Reset to defaults</button>
      </div>
      <div style={{overflowX:'auto',overflowY:'auto',maxHeight:'calc(100vh - 240px)'}}>
        <table style={{width:'100%',borderCollapse:'collapse',minWidth:700}}>
          <thead style={{position:'sticky',top:0,background:'#f5f0e8',zIndex:2}}>
            <tr>
              <th style={{...thS,width:28}}></th>
              <th style={thS}>Start</th><th style={thS}>End</th>
              <th style={thS}>Holder</th><th style={thS}>Label</th>
              <th style={thS}>Colour</th><th style={thS}>Source</th>
              <th style={{...thS,width:28}}>V</th><th style={thS}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {viStatus.map((p,i) => {
              const isExp = exp===i;
              return (
                <React.Fragment key={i}>
                  <tr style={{background:isExp?'#f0ebe3':i%2===0?'#fff':'#faf7f3',cursor:'pointer'}} onClick={()=>setExp(isExp?null:i)}>
                    <td style={{...tdS,textAlign:'center',fontSize:11,color:'#c4a87a',userSelect:'none'}}>{isExp?'▼':'▶'}</td>
                    <td style={{...tdS,width:85}}><input style={iS} type="number" value={p.startYear} onClick={e=>e.stopPropagation()} onChange={e=>{e.stopPropagation();upd(i,'startYear',e.target.value)}}/></td>
                    <td style={{...tdS,width:85}}><input style={iS} type="number" value={p.endYear}   onClick={e=>e.stopPropagation()} onChange={e=>{e.stopPropagation();upd(i,'endYear',e.target.value)}}/></td>
                    <td style={{...tdS,width:100}} onClick={e=>e.stopPropagation()}>
                      <select style={iS} value={p.holder} onChange={e=>upd(i,'holder',e.target.value)}>
                        {Object.entries(POWERS).map(([k,v])=><option key={k} value={k}>{v.short}</option>)}
                      </select>
                    </td>
                    <td style={{...tdS,minWidth:160}}><input style={iS} value={p.label} onClick={e=>e.stopPropagation()} onChange={e=>{e.stopPropagation();upd(i,'label',e.target.value)}}/></td>
                    <td style={{...tdS,width:80}} onClick={e=>e.stopPropagation()}>
                      <div style={{display:'flex',alignItems:'center',gap:4}}>
                        <input type="color" value={p.color} onChange={e=>upd(i,'color',e.target.value)} style={{width:26,height:20,border:'none',cursor:'pointer',padding:0,borderRadius:2}}/>
                        <span style={{fontSize:9,fontFamily:'monospace',color:'#7a6a55'}}>{p.color}</span>
                      </div>
                    </td>
                    <td style={{...tdS,fontSize:11,color:'#6b5a45',maxWidth:140}} onClick={e=>e.stopPropagation()}>
                      <span style={{opacity:0.7}}>{p.source ? p.source.slice(0,30)+(p.source.length>30?'…':'') : <em style={{color:'#ccc'}}>no source</em>}</span>
                    </td>
                    <td style={{...tdS,textAlign:'center'}} onClick={e=>e.stopPropagation()}><VerifiedBadge verified={p.verified}/></td>
                    <td style={{...tdS,width:220}} onClick={e=>e.stopPropagation()}>
                      <div style={{display:'flex',gap:4}}>
                        <ActBtn label="Move up" onClick={()=>mov(i,-1)}/><ActBtn label="Move down" onClick={()=>mov(i,1)}/><ActBtn label="Delete" onClick={()=>del(i)} danger/>
                      </div>
                    </td>
                  </tr>
                  {isExp && <SourcePanel item={p} onUpdate={(f,v)=>upd(i,f,v)}/>}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ── PEOPLE EDITOR ─────────────────────────────────────────────────────────────
function PeopleEditor({ people, setPeople, roleTags, monarchs, setMonarchs, viGovs, setViGovs, liGovs, setLiGovs }) {
  const [exp, setExp] = useState(null);
  const [showMig, setShowMig] = useState(false);

  function upd(i,f,v) {
    const numF = ['birthYear','birthMonth','birthDay','deathYear','deathMonth','deathDay'];
    setPeople(p=>p.map((x,j)=>j!==i?x:{...x,[f]:numF.includes(f)?(parseInt(v)||undefined):v}));
  }
  function toggleTag(i, tagId) {
    setPeople(p=>p.map((x,j)=>{
      if (j!==i) return x;
      const tags = new Set(x.roleTags||[]);
      tags.has(tagId) ? tags.delete(tagId) : tags.add(tagId);
      return {...x, roleTags:[...tags]};
    }));
  }
  function add() {
    const id = 'u_p_'+Date.now();
    setPeople(p=>[...p, { id, name:'New Person', aliases:'', birthYear:null, deathYear:null, birthCal:'greg', deathCal:'greg', roleTags:[], power:'GBR', biography:'', source:'', citation:'', verified:false, notes:'' }]);
    setExp(people.length);
  }
  function del(i) {
    if (!confirm('Delete this person? Any cross-references will be unlinked.')) return;
    const pid = people[i].id;
    // Unlink from monarchs/governors
    setMonarchs(p=>p.map(m=>m.personId===pid?{...m, personId:null}:m));
    setViGovs(p=>p.map(g=>g.personId===pid?{...g, personId:null}:g));
    setLiGovs(p=>p.map(g=>g.personId===pid?{...g, personId:null}:g));
    setPeople(p=>p.filter((_,j)=>j!==i));
    setExp(null);
  }
  function mov(i,d) { setPeople(p=>{ const a=[...p],j=i+d; if(j<0||j>=a.length) return a; [a[i],a[j]]=[a[j],a[i]]; return a; }); }

  // Auto-link helper: scan governors/monarchs for unlinked names, create stub people
  function autoMigrate() {
    const existingNames = new Set(people.map(p => p.name.toLowerCase().trim()));
    const created = [];
    function consider(name, roleTag, sourceList) {
      if (!name || name.startsWith('(')) return null; // skip "(Various...)" placeholders
      const key = name.toLowerCase().trim();
      if (existingNames.has(key)) {
        // Already a person — just need the link
        return people.find(p => p.name.toLowerCase().trim()===key)?.id;
      }
      const id = 'm_p_' + Date.now() + '_' + created.length;
      created.push({
        id, name, aliases:'', birthYear:null, deathYear:null, birthCal:'greg', deathCal:'greg',
        roleTags:[roleTag], power:'GBR', biography:'', source:'', citation:'', verified:false,
        notes:'Auto-created from '+sourceList+' \u2014 needs research.'
      });
      existingNames.add(key);
      return id;
    }
    const newMonarchs = monarchs.map(m => m.personId ? m : (m.name.startsWith('(')||m.name==='Commonwealth' ? m : { ...m, personId: consider(m.name, 'monarch', 'UK_MONARCHS') }));
    const newLi = liGovs.map(g => g.personId ? g : { ...g, personId: consider(g.name, 'gov_li', 'LI_GOVERNORS') });
    const newVi = viGovs.map(g => g.personId ? g : { ...g, personId: consider(g.name, 'gov_vi', 'VI_GOVERNORS') });
    setPeople(p => [...p, ...created]);
    setMonarchs(newMonarchs);
    setLiGovs(newLi);
    setViGovs(newVi);
    setShowMig(false);
    alert(`Auto-migration complete. Created ${created.length} new person record(s).`);
  }

  function dispDate(y,m,d,cal) {
    if(!y) return '?';
    const s = `${d?d+' ':''}${m?TU.MONTHS_SHORT[m-1]+' ':''}${y}`;
    return cal==='julian' ? s+' (O.S.)' : s;
  }
  function lifespan(p) {
    const b = p.birthYear ? dispDate(p.birthYear,p.birthMonth,p.birthDay,p.birthCal) : '?';
    const d = p.deathYear ? dispDate(p.deathYear,p.deathMonth,p.deathDay,p.deathCal) : '?';
    if (b==='?' && d==='?') return '\u2014';
    return `${b} \u2013 ${d}`;
  }
  function linkedRoles(p) {
    const out = [];
    monarchs.forEach(m => { if (m.personId===p.id) out.push(`Monarch (${m.sYear||'?'}\u2013${m.eYear||'?'})`); });
    liGovs.forEach(g => { if (g.personId===p.id) out.push(`LI ${g.title||'Gov'} (${g.startYear||'?'}\u2013${g.endYear||'?'})`); });
    viGovs.forEach(g => { if (g.personId===p.id) out.push(`VI ${g.title||'Gov'} (${g.startYear||'?'}\u2013${g.endYear||'?'})`); });
    return out;
  }

  return (
    <>
      <div style={{display:'flex',gap:8,marginBottom:10,flexWrap:'wrap'}}>
        <button onClick={add} style={{padding:'5px 14px',fontSize:12,border:'none',borderRadius:4,background:'#8b1a1a',color:'#fff',cursor:'pointer'}}>+ Add Person</button>
        <button onClick={()=>setShowMig(true)} style={{padding:'5px 14px',fontSize:12,border:'1px solid #00695c',borderRadius:4,background:'#fff',color:'#00695c',cursor:'pointer'}}>\u2192 Auto-link existing governors/monarchs</button>
        <button onClick={()=>{ if(confirm('Reset people to original seed data? This will not affect cross-references on governors/monarchs.')) { setPeople(PEOPLE); setExp(null); } }}
          style={{padding:'5px 14px',fontSize:12,border:'1px solid #c4b49a',borderRadius:4,background:'#fff',color:'#7a5a20',cursor:'pointer'}}>Reset to defaults</button>
      </div>

      {showMig && (
        <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,0.55)',zIndex:200,display:'flex',alignItems:'center',justifyContent:'center'}}
          onClick={e=>e.target===e.currentTarget && setShowMig(false)}>
          <div style={{background:'#fdf9f4',borderRadius:8,padding:'24px 28px',maxWidth:500,boxShadow:'0 8px 40px rgba(0,0,0,0.3)'}}>
            <h3 style={{margin:'0 0 12px',fontFamily:'Georgia,serif',fontSize:17,color:'#2d1f0e'}}>Auto-link existing governors & monarchs</h3>
            <p style={{fontSize:13,lineHeight:1.6,color:'#3a2e1e'}}>This will scan UK Monarchs, LI Governors and VI Governors for entries that are <strong>not yet linked</strong> to a person record, and create stub person records for them.</p>
            <p style={{fontSize:12,lineHeight:1.6,color:'#7a6a55',marginTop:8}}>Names matching existing people are linked automatically. Placeholder rows like <em>(Various Presidents)</em> are skipped. Created stubs are tagged with the relevant role and marked unverified.</p>
            <div style={{display:'flex',gap:10,justifyContent:'flex-end',marginTop:18}}>
              <button onClick={()=>setShowMig(false)} style={{padding:'7px 16px',border:'1px solid #c4b49a',borderRadius:4,background:'#fff',cursor:'pointer',fontSize:13}}>Cancel</button>
              <button onClick={autoMigrate} style={{padding:'7px 16px',border:'none',borderRadius:4,background:'#00695c',color:'#fff',cursor:'pointer',fontSize:13,fontWeight:600}}>Run migration</button>
            </div>
          </div>
        </div>
      )}

      <div style={{overflowX:'auto',overflowY:'auto',maxHeight:'calc(100vh - 280px)'}}>
        <table style={{width:'100%',borderCollapse:'collapse',minWidth:800}}>
          <thead style={{position:'sticky',top:0,background:'#f5f0e8',zIndex:2}}>
            <tr>
              <th style={{...thS,width:28}}></th>
              <th style={thS}>Name</th>
              <th style={thS}>Lifespan</th>
              <th style={thS}>Roles</th>
              <th style={thS}>Linked</th>
              <th style={{...thS,width:28}}>V</th>
              <th style={thS}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {people.map((p,i) => {
              const isExp = exp===i;
              const links = linkedRoles(p);
              return (
                <React.Fragment key={p.id||i}>
                  <tr style={{background:isExp?'#f0ebe3':i%2===0?'#fff':'#faf7f3',cursor:'pointer'}} onClick={()=>setExp(isExp?null:i)}>
                    <td style={{...tdS,textAlign:'center',fontSize:11,color:'#c4a87a',userSelect:'none'}}>{isExp?'\u25bc':'\u25b6'}</td>
                    <td style={{...tdS,minWidth:180}}>
                      <input style={iS} value={p.name} onClick={e=>e.stopPropagation()} onChange={e=>{e.stopPropagation();upd(i,'name',e.target.value)}}/>
                      {p.aliases && <div style={{fontSize:9,color:'#8a7a68',marginTop:2,fontStyle:'italic'}}>{p.aliases}</div>}
                    </td>
                    <td style={{...tdS,fontSize:11,color:'#6b5a45',whiteSpace:'nowrap'}}>{lifespan(p)}</td>
                    <td style={{...tdS,minWidth:180}}>
                      <div style={{display:'flex',flexWrap:'wrap',gap:3}}>
                        {(p.roleTags||[]).map(tid => {
                          const t = roleTags.find(r=>r.id===tid);
                          if (!t) return null;
                          return <span key={tid} style={{padding:'1px 6px',borderRadius:3,fontSize:10,background:t.color+'22',color:t.color,border:`1px solid ${t.color}55`}}>{t.label}</span>;
                        })}
                        {(!p.roleTags || p.roleTags.length===0) && <span style={{fontSize:10,color:'#bbb',fontStyle:'italic'}}>no tags</span>}
                      </div>
                    </td>
                    <td style={{...tdS,fontSize:10,color:'#7a6a55'}}>
                      {links.length === 0 ? <span style={{color:'#bbb',fontStyle:'italic'}}>\u2014</span> : links.map((l,k)=><div key={k}>{l}</div>)}
                    </td>
                    <td style={{...tdS,textAlign:'center'}} onClick={e=>e.stopPropagation()}><VerifiedBadge verified={p.verified}/></td>
                    <td style={{...tdS,width:220}} onClick={e=>e.stopPropagation()}>
                      <div style={{display:'flex',gap:4}}>
                        <ActBtn label="Move up" onClick={()=>mov(i,-1)}/><ActBtn label="Move down" onClick={()=>mov(i,1)}/><ActBtn label="Delete" onClick={()=>del(i)} danger/>
                      </div>
                    </td>
                  </tr>
                  {isExp && (
                    <tr>
                      <td colSpan={7} style={{background:'#f0ebe3',padding:'14px 20px 16px 44px',borderBottom:'2px solid #d4c8b8'}}>
                        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,maxWidth:840}}>
                          <div>
                            <label style={labelS}>Aliases / Other names</label>
                            <input style={iS} value={p.aliases||''} onChange={e=>upd(i,'aliases',e.target.value)} placeholder="e.g. Lord Mansfield"/>
                          </div>
                          <div>
                            <label style={labelS}>Power / Allegiance</label>
                            <select style={iS} value={p.power||'GBR'} onChange={e=>upd(i,'power',e.target.value)}>
                              {Object.entries(POWERS).map(([k,v])=><option key={k} value={k}>{v.label}</option>)}
                            </select>
                          </div>
                          <DateInput label="Born" year={p.birthYear} month={p.birthMonth} day={p.birthDay} cal={p.birthCal||'greg'}
                            onChange={(f,v)=>upd(i, f==='cal'?'birthCal':'birth'+f.charAt(0).toUpperCase()+f.slice(1), v)}/>
                          <DateInput label="Died" year={p.deathYear} month={p.deathMonth} day={p.deathDay} cal={p.deathCal||'greg'}
                            onChange={(f,v)=>upd(i, f==='cal'?'deathCal':'death'+f.charAt(0).toUpperCase()+f.slice(1), v)}/>
                          <div style={{gridColumn:'1/-1'}}>
                            <label style={labelS}>Role tags <span style={{color:'#a09080',fontSize:9,fontWeight:400,textTransform:'none',letterSpacing:0}}>(click to toggle; manage list in Role Tags section)</span></label>
                            <div style={{display:'flex',flexWrap:'wrap',gap:5}}>
                              {roleTags.map(t => {
                                const on = (p.roleTags||[]).includes(t.id);
                                return (
                                  <button key={t.id} onClick={()=>toggleTag(i,t.id)} style={{padding:'3px 9px',fontSize:11,borderRadius:3,cursor:'pointer',
                                    background:on?t.color+'33':'#fff',
                                    color:on?t.color:'#888',
                                    border:`1px solid ${on?t.color+'aa':'#d4c8b8'}`,
                                    fontWeight:on?600:400}}>{t.label}</button>
                                );
                              })}
                            </div>
                          </div>
                          <div style={{gridColumn:'1/-1'}}>
                            <label style={labelS}>Biography</label>
                            <textarea style={{...iS,height:70,resize:'vertical',fontFamily:'inherit'}} value={p.biography||''} onChange={e=>upd(i,'biography',e.target.value)} placeholder="Short biographical paragraph\u2026"/>
                          </div>
                          <div>
                            <label style={labelS}>Source</label>
                            <input style={iS} value={p.source||''} onChange={e=>upd(i,'source',e.target.value)} placeholder="e.g. Oxford DNB"/>
                          </div>
                          <div>
                            <label style={labelS}>Citation / Reference</label>
                            <input style={iS} value={p.citation||''} onChange={e=>upd(i,'citation',e.target.value)} placeholder="e.g. ODNB ref."/>
                          </div>
                          <div style={{gridColumn:'1/-1'}}>
                            <label style={labelS}>Research Notes</label>
                            <textarea style={{...iS,height:50,resize:'vertical',fontFamily:'inherit'}} value={p.notes||''} onChange={e=>upd(i,'notes',e.target.value)}/>
                          </div>
                          <div style={{gridColumn:'1/-1'}}>
                            <label style={{display:'flex',alignItems:'center',gap:8,cursor:'pointer',fontSize:12,color:'#3a2e1e'}}>
                              <input type="checkbox" checked={!!p.verified} onChange={e=>upd(i,'verified',e.target.checked)} style={{width:15,height:15,accentColor:'#2e7d32'}}/>
                              <span>Verified against primary source</span>
                            </label>
                          </div>
                          {links.length > 0 && (
                            <div style={{gridColumn:'1/-1',padding:'8px 12px',background:'#fff',borderRadius:4,border:'1px solid #d4c8b8'}}>
                              <div style={{...labelS,marginBottom:6}}>Cross-references</div>
                              {links.map((l,k)=><div key={k} style={{fontSize:11,color:'#3a2e1e',padding:'2px 0'}}>\u2192 {l}</div>)}
                            </div>
                          )}
                        </div>
                      </td>
                    </tr>
                  )}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>
      <div style={{marginTop:8,fontSize:11,color:'#a09080'}}>People are the canonical biographical register. Governors and monarchs link here via their <code>personId</code>. Click a row to expand; click any role tag to toggle.</div>
    </>
  );
}

// ── ROLE TAGS EDITOR ──────────────────────────────────────────────────────────
function RoleTagsEditor({ roleTags, setRoleTags, people }) {
  function upd(i,f,v) { setRoleTags(p=>p.map((t,j)=>j!==i?t:{...t,[f]:v})); }
  function add() { setRoleTags(p=>[...p,{id:'tag_'+Date.now(),label:'New Tag',color:'#888888'}]); }
  function del(i) {
    const tag = roleTags[i];
    const used = people.filter(p => (p.roleTags||[]).includes(tag.id)).length;
    if (used > 0 && !confirm(`This tag is used by ${used} person record(s). Delete anyway?`)) return;
    if (used === 0 && !confirm('Delete this tag?')) return;
    setRoleTags(p=>p.filter((_,j)=>j!==i));
  }
  function mov(i,d) { setRoleTags(p=>{ const a=[...p],j=i+d; if(j<0||j>=a.length) return a; [a[i],a[j]]=[a[j],a[i]]; return a; }); }
  function countUse(tagId) { return people.filter(p => (p.roleTags||[]).includes(tagId)).length; }

  return (
    <>
      <div style={{display:'flex',gap:8,marginBottom:10}}>
        <button onClick={add} style={{padding:'5px 14px',fontSize:12,border:'none',borderRadius:4,background:'#8b1a1a',color:'#fff',cursor:'pointer'}}>+ Add Tag</button>
        <button onClick={()=>{ if(confirm('Reset role tags to defaults?')) setRoleTags(ROLE_TAGS); }}
          style={{padding:'5px 14px',fontSize:12,border:'1px solid #c4b49a',borderRadius:4,background:'#fff',color:'#7a5a20',cursor:'pointer'}}>Reset to defaults</button>
      </div>
      <table style={{width:'100%',borderCollapse:'collapse',maxWidth:700}}>
        <thead style={{background:'#f5f0e8'}}>
          <tr><th style={thS}>ID</th><th style={thS}>Label</th><th style={thS}>Colour</th><th style={thS}>Used by</th><th style={thS}>Actions</th></tr>
        </thead>
        <tbody>
          {roleTags.map((t,i) => (
            <tr key={t.id} style={{background:i%2===0?'#fff':'#faf7f3'}}>
              <td style={{...tdS,fontFamily:'monospace',fontSize:11,color:'#7a6a55'}}>{t.id}</td>
              <td style={{...tdS,minWidth:180}}><input style={iS} value={t.label} onChange={e=>upd(i,'label',e.target.value)}/></td>
              <td style={{...tdS,width:100}}>
                <div style={{display:'flex',alignItems:'center',gap:4}}>
                  <input type="color" value={t.color} onChange={e=>upd(i,'color',e.target.value)} style={{width:26,height:20,border:'none',cursor:'pointer',padding:0,borderRadius:2}}/>
                  <span style={{fontSize:9,fontFamily:'monospace',color:'#7a6a55'}}>{t.color}</span>
                </div>
              </td>
              <td style={{...tdS,fontSize:11,color:'#7a6a55'}}>{countUse(t.id)} {countUse(t.id)===1?'person':'people'}</td>
              <td style={{...tdS,width:200}}>
                <div style={{display:'flex',gap:4}}>
                  <ActBtn label="Move up"   onClick={()=>mov(i,-1)}/>
                  <ActBtn label="Move down" onClick={()=>mov(i,1)}/>
                  <ActBtn label="Delete"    onClick={()=>del(i)} danger/>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      <div style={{marginTop:8,fontSize:11,color:'#a09080'}}>Tag IDs are referenced by person records. Renaming a tag's <em>label</em> is safe; changing the <em>ID</em> is not currently supported.</div>
    </>
  );
}

// ── PERSON LINK DROPDOWN (used in monarchs/governors editors) ─────────────────
function PersonLink({ value, onChange, people, suggestedName }) {
  const sorted = useMemo(()=>[...people].sort((a,b)=>a.name.localeCompare(b.name)),[people]);
  const linked = people.find(p=>p.id===value);
  return (
    <div style={{display:'flex',alignItems:'center',gap:4}}>
      <select style={{...iS,fontSize:11,padding:'2px 4px'}} value={value||''} onChange={e=>onChange(e.target.value||null)}>
        <option value="">\u2014 unlinked \u2014</option>
        {sorted.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
      </select>
      {linked && <span style={{fontSize:10,color:'#00695c'}}>\u2713</span>}
    </div>
  );
}

// ── MAIN REFERENCE EDITOR ─────────────────────────────────────────────────────
function ReferenceEditor({ monarchs, setMonarchs, viStatus, setViStatus, wars, setWars, viGovs, setViGovs, liGovs, setLiGovs, people, setPeople, roleTags, setRoleTags }) {
  const [section, setSection] = useState('monarchs');

  const sections = [
    { id:'monarchs', label:'UK Monarchs' },
    { id:'vi',       label:'VI Colonial Status' },
    { id:'wars',     label:'Wars' },
    { id:'vigov',    label:'VI Governors' },
    { id:'ligov',    label:'Leeward Is. Governors' },
    { id:'people',   label:'People' },
    { id:'tags',     label:'Role Tags' },
  ];

  const tabBtn = (id, label) => (
    <button key={id} onClick={()=>setSection(id)} style={{padding:'5px 14px',fontSize:12,border:'none',cursor:'pointer',fontWeight:section===id?600:400,
      background:section===id?'#8b1a1a':'#e8e0d0',color:section===id?'#fff':'#5a4a38',borderRadius:4}}>
      {label}
    </button>
  );

  return (
    <div style={{maxWidth:1100}}>
      <div style={{marginBottom:14,display:'flex',alignItems:'center',gap:6,flexWrap:'wrap'}}>
        {sections.map(s => tabBtn(s.id, s.label))}
        <span style={{fontSize:11,color:'#a09080',marginLeft:8}}>Click ▶ on any row to add source & notes. Changes save automatically.</span>
      </div>
      {section==='monarchs' && <MonarchEditor monarchs={monarchs} setMonarchs={setMonarchs} people={people}/>}
      {section==='vi'       && <VIStatusEditor viStatus={viStatus} setViStatus={setViStatus}/>}
      {section==='wars'     && <WarsEditor wars={wars} setWars={setWars}/>}
      {section==='vigov'    && <GovernorEditor govs={viGovs} setGovs={setViGovs} defaultData={VI_GOVERNORS} label="VI Governors" people={people}/>}
      {section==='ligov'    && <GovernorEditor govs={liGovs} setGovs={setLiGovs} defaultData={LI_GOVERNORS} label="Leeward Islands Governors" people={people}/>}
      {section==='people'   && <PeopleEditor people={people} setPeople={setPeople} roleTags={roleTags} monarchs={monarchs} setMonarchs={setMonarchs} viGovs={viGovs} setViGovs={setViGovs} liGovs={liGovs} setLiGovs={setLiGovs}/>}
      {section==='tags'     && <RoleTagsEditor roleTags={roleTags} setRoleTags={setRoleTags} people={people}/>}
    </div>
  );
}

Object.assign(window, { ReferenceEditor });
