/* ============================================================
 * Developer · Project Detail (data-driven) + Phase-3 Workspace.
 *
 * The project detail supports three layout variants exposed via
 * the Tweaks panel:
 *   - 'scroll' (default): single-scroll, content + sidebar
 *   - 'tabs'  : Overview / Phase / Trust / Issuance tabs
 *   - 'accordion': stacked accordion sections
 *
 * The detail page reads project.id and looks up everything from
 * the canonical dataset — no NaN, no undefined.
 * ============================================================ */

function ProjectDetail({ project, layout = 'scroll', onBack, onOpenPhase, onOpenFindings, findings }) {
  if (!project) return null;
  const findingsForThis = (findings || []).filter(f => f.projectId === project.id || project.hero); // hero gets all sample findings
  const findingsOpen = findingsForThis.filter(f=>f.status==='open').length;

  return (
    <main style={{flex:1, padding:'28px 32px', background:'#F9FAFB', minWidth:0}}>
      <button onClick={onBack} style={{
        background:'transparent', border:'none', color:'#B8960A',
        fontSize:12, fontWeight:700, cursor:'pointer', padding:0, marginBottom:14,
        display:'inline-flex', alignItems:'center', gap:6, whiteSpace:'nowrap',
      }}>
        <PamojaIcon name="back" size={12} color="#B8960A" stroke={2.2}/>
        Back to projects
      </button>

      <ProjectDetailHeader project={project} onOpenPhase={onOpenPhase} findingsOpen={findingsOpen} onOpenFindings={onOpenFindings}/>

      {layout === 'tabs' && <ProjectDetailTabs project={project} findings={findingsForThis} onOpenFindings={onOpenFindings} onOpenPhase={onOpenPhase}/>}
      {layout === 'accordion' && <ProjectDetailAccordion project={project} findings={findingsForThis} onOpenFindings={onOpenFindings} onOpenPhase={onOpenPhase}/>}
      {layout === 'scroll' && <ProjectDetailScroll project={project} findings={findingsForThis} onOpenFindings={onOpenFindings} onOpenPhase={onOpenPhase}/>}
    </main>
  );
}

function ProjectDetailHeader({ project, onOpenPhase, findingsOpen, onOpenFindings }) {
  return (
    <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:24, marginBottom:20, flexWrap:'wrap'}}>
      <div style={{minWidth:0}}>
        <div style={{fontFamily:'JetBrains Mono, monospace', fontSize:11, color:'#9CA3AF', marginBottom:4, letterSpacing:'0.04em'}}>{project.id}</div>
        <h1 style={{fontSize:28, fontWeight:900, color:'#022C28', letterSpacing:'-0.02em', margin:'0 0 10px'}}>{project.name}</h1>
        <div style={{display:'flex', gap:8, alignItems:'center', flexWrap:'wrap'}}>
          <Badge variant={project.registryVariant} mono>{project.registry}</Badge>
          <Badge variant={project.statusVariant} dot>{project.status}</Badge>
          <Badge variant="gray">Phase {project.phase} · {project.phaseName}</Badge>
          <span style={{fontSize:12, color:'#6B7280', display:'inline-flex', alignItems:'center', gap:6}}>
            <PamojaIcon name="pin" size={12} color="#9CA3AF" stroke={1.7}/>
            {project.location}
          </span>
          <span style={{fontSize:12, color:'#6B7280'}}>· {project.methodologyName}</span>
        </div>
      </div>
      <div style={{display:'flex', gap:8, flexWrap:'wrap'}}>
        {findingsOpen > 0 && (
          <Btn kind="secondary" onClick={onOpenFindings} icon="flag" style={{borderColor:'#FBBF24', color:'#92400E'}}>
            {findingsOpen} VVB finding{findingsOpen>1?'s':''}
          </Btn>
        )}
        <Btn kind="secondary">VVB Gap Report</Btn>
        <Btn kind="primary" onClick={()=>onOpenPhase(project)} icon="edit">Open Phase {project.phase}</Btn>
      </div>
    </div>
  );
}

/* --- Variant 1: scroll layout (default) --------------------- */
function ProjectDetailScroll({ project, findings, onOpenFindings, onOpenPhase }) {
  return (
    <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap:20}}>
      <div style={{display:'flex', flexDirection:'column', gap:20}}>
        <PhaseSection project={project} onOpenPhase={onOpenPhase}/>
        <FieldsPreview project={project} onOpenPhase={onOpenPhase}/>
        <FindingsPreview project={project} findings={findings} onOpenFindings={onOpenFindings}/>
        <AuditTrailPreview project={project}/>
      </div>
      <aside style={{display:'flex', flexDirection:'column', gap:20}}>
        <ReadinessCard project={project}/>
        <CreditsCard project={project}/>
        <ProjectMetaCard project={project}/>
      </aside>
    </div>
  );
}

/* --- Variant 2: tabs layout --------------------------------- */
function ProjectDetailTabs({ project, findings, onOpenFindings, onOpenPhase }) {
  const [tab, setTab] = React.useState('overview');
  const tabs = [
    { id:'overview',  label:'Overview' },
    { id:'phase',     label:`Phase ${project.phase}` },
    { id:'findings',  label:`Findings`, count: findings.filter(f=>f.status==='open').length },
    { id:'trust',     label:'Trust trail' },
    { id:'credits',   label:'Credits' },
  ];
  return (
    <div>
      <div style={{display:'flex', gap:0, borderBottom:'1px solid #E5E7EB', marginBottom:20}}>
        {tabs.map(t => (
          <button key={t.id} onClick={()=>setTab(t.id)} style={{
            background:'transparent', border:'none', cursor:'pointer',
            padding:'12px 16px', fontFamily:'inherit',
            fontSize:13, fontWeight: tab===t.id ? 800 : 600,
            color: tab===t.id ? '#022C28' : '#6B7280',
            borderBottom: tab===t.id ? '2px solid #F4C300' : '2px solid transparent',
            marginBottom:-1, display:'inline-flex', alignItems:'center', gap:8,
          }}>
            {t.label}
            {t.count > 0 && <span style={{background:'#FEF3C7', color:'#92400E', fontSize:10, fontWeight:800, padding:'2px 7px', borderRadius:9999}}>{t.count}</span>}
          </button>
        ))}
      </div>
      <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap:20}}>
        <div style={{display:'flex', flexDirection:'column', gap:20}}>
          {tab === 'overview' && <><PhaseSection project={project} onOpenPhase={onOpenPhase}/><ProjectMetaCard project={project} expanded/></>}
          {tab === 'phase' && <FieldsPreview project={project} onOpenPhase={onOpenPhase} full/>}
          {tab === 'findings' && <FindingsPreview project={project} findings={findings} onOpenFindings={onOpenFindings} full/>}
          {tab === 'trust' && <AuditTrailPreview project={project} full/>}
          {tab === 'credits' && <CreditsExpanded project={project}/>}
        </div>
        <aside style={{display:'flex', flexDirection:'column', gap:20}}>
          <ReadinessCard project={project}/>
          {tab !== 'credits' && <CreditsCard project={project}/>}
        </aside>
      </div>
    </div>
  );
}

/* --- Variant 3: accordion layout ---------------------------- */
function ProjectDetailAccordion({ project, findings, onOpenFindings, onOpenPhase }) {
  const [open, setOpen] = React.useState({ phase:true, fields:true, findings:false, trail:false, credits:false });
  const toggle = (k) => setOpen({...open, [k]:!open[k]});
  const findingsOpen = findings.filter(f=>f.status==='open').length;
  const sections = [
    { id:'phase',    title:`Phase ${project.phase} · ${project.phaseName}`, badge: `${project.vvb}/100 readiness`, render:()=>(<><PhaseSection project={project} onOpenPhase={onOpenPhase}/></>) },
    { id:'fields',   title:'Phase fields', badge:`${project.phases.find(p=>p.state==='current')?.detail || '—'}`, render:()=><FieldsPreview project={project} onOpenPhase={onOpenPhase} full/> },
    { id:'findings', title:'VVB findings & CAPs', badge: findingsOpen ? `${findingsOpen} open` : 'None', render:()=><FindingsPreview project={project} findings={findings} onOpenFindings={onOpenFindings} full/> },
    { id:'trail',    title:'Hedera audit trail', badge:'Live', render:()=><AuditTrailPreview project={project} full/> },
    { id:'credits',  title:'Credits & issuance', badge: project.credits ? `${project.credits.toLocaleString()} issued` : `${project.projected.toLocaleString()} projected`, render:()=><CreditsExpanded project={project}/> },
  ];
  return (
    <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap:20}}>
      <div style={{display:'flex', flexDirection:'column', gap:8}}>
        {sections.map(s => (
          <div key={s.id} style={{background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, overflow:'hidden'}}>
            <button onClick={()=>toggle(s.id)} style={{
              width:'100%', textAlign:'left', background:'transparent', border:'none', cursor:'pointer',
              padding:'16px 22px', display:'flex', alignItems:'center', justifyContent:'space-between',
              fontFamily:'inherit',
            }}>
              <div style={{display:'flex', alignItems:'center', gap:14}}>
                <div style={{transform: open[s.id] ? 'rotate(180deg)' : 'rotate(0)', transition:'transform 200ms'}}>
                  <PamojaIcon name="chevronDown" size={14} color="#022C28" stroke={2.2}/>
                </div>
                <span style={{fontSize:15, fontWeight:800, color:'#022C28'}}>{s.title}</span>
              </div>
              <span style={{fontSize:11, color:'#6B7280', fontWeight:600}}>{s.badge}</span>
            </button>
            {open[s.id] && (
              <div style={{padding:'0 22px 22px'}}>
                {s.render()}
              </div>
            )}
          </div>
        ))}
      </div>
      <aside style={{display:'flex', flexDirection:'column', gap:20}}>
        <ReadinessCard project={project}/>
        <CreditsCard project={project}/>
        <ProjectMetaCard project={project}/>
      </aside>
    </div>
  );
}

/* ===== Section building blocks ============================== */

function PhaseSection({ project, onOpenPhase }) {
  return (
    <div style={{background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, padding:24}}>
      <SectionHeader eyebrow={`Compliance · ${project.methodology}`} title="Phase progress" tail={project.phases.find(p=>p.state==='current')?.detail || 'Complete'}/>
      <div style={{marginTop:14}}>
        <PhaseTrackInline phases={project.phases}/>
      </div>
      <div style={{marginTop:16, paddingTop:16, borderTop:'1px dashed #E5E7EB', display:'flex', justifyContent:'space-between', alignItems:'center', gap:14}}>
        <div style={{fontSize:12, color:'#6B7280'}}>
          Continue editing Phase {project.phase} fields with AI-assisted extraction.
        </div>
        <Btn kind="primary" onClick={()=>onOpenPhase(project)} icon="edit">Open Phase {project.phase}</Btn>
      </div>
    </div>
  );
}

function FieldsPreview({ project, onOpenPhase, full = false }) {
  // For the hero project we have real PHASE3_FIELDS; for others, generate synthetic ones.
  const fields = project.id === 'PRJ-KE-BUS001' ? PHASE3_FIELDS : syntheticFields(project);
  const shown = full ? fields : fields.slice(0, 8);
  return (
    <div style={{background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, padding:24}}>
      <SectionHeader
        eyebrow={`Phase ${project.phase} · ${project.phaseName}`}
        title="Project design fields"
        tail={`${fields.filter(f=>f.state==='confirmed'||f.state==='committed'||f.state==='imported').length} of ${fields.length} confirmed`}
      />
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginTop:14}}>
        {shown.map(f => (
          <FieldRow key={f.id} state={f.state} label={f.label} value={f.value} who={f.who} onClick={()=>onOpenPhase(project)}/>
        ))}
      </div>
      {!full && fields.length > 8 && (
        <div style={{marginTop:14, textAlign:'center'}}>
          <Btn kind="secondary" onClick={()=>onOpenPhase(project)}>
            View all {fields.length} fields →
          </Btn>
        </div>
      )}
    </div>
  );
}

function syntheticFields(project) {
  // For non-hero projects, fewer fields, mostly empty/confirmed.
  const base = [
    { id:'method',     label:'Methodology',           state: project.phase >= 2 ? 'imported' : 'empty',  value: project.methodology,    who: 'Verra Registry API' },
    { id:'area',       label:'Project area',          state: project.phase >= 2 ? 'confirmed' : 'empty', value: project.area,            who: 'Grace K.' },
    { id:'species',    label:'Species mix',           state: project.phase >= 2 ? 'confirmed' : 'empty', value: project.species,         who: 'Grace K.' },
    { id:'households', label:'Households participating', state: 'confirmed',                              value: project.households.toLocaleString(), who:'Field census · Mar 2026' },
    { id:'baseline',   label:'Baseline carbon stock', state: project.phase >= 3 ? 'ai' : 'empty',        value: project.phase>=3 ? '42.1 tC/ha (±5.0)' : '—', who: project.phase>=3 ? 'Extracted PDD · 86% conf.' : 'Pending PDD' },
    { id:'monitoring', label:'Monitoring plan',       state: project.phase >= 3 ? 'confirmed' : 'empty', value: project.phase>=3 ? 'Annual + 5-yr full inventory' : '—', who: project.phase>=3 ? 'Grace K.' : 'Pending' },
    { id:'tenure',     label:'Land tenure',           state: 'empty',                                    value: '—',                     who: 'Required' },
    { id:'fpic',       label:'FPIC consent',          state: project.phase >= 2 ? 'confirmed' : 'empty', value: project.phase>=2 ? `${project.households} signatures` : '—', who: project.phase>=2 ? 'Field agents' : 'Pending' },
  ];
  return base;
}

function FindingsPreview({ project, findings, onOpenFindings, full = false }) {
  const has = findings && findings.length > 0;
  return (
    <div style={{background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, padding:24}}>
      <SectionHeader eyebrow="Trust · Read-only" title="VVB findings" tail={has ? `${findings.filter(f=>f.status==='open').length} open` : 'No findings raised'}/>
      <div style={{fontSize:12, color:'#6B7280', marginTop:6, marginBottom:14, lineHeight:1.5}}>
        Findings raised by the assigned VVB auditor. You can post a response and attach evidence — sampling and sign-off are VVB actions only.
      </div>
      {!has && <EmptyState icon="check" title="No findings yet" body="Your VVB has not raised any findings on this project. You'll be notified here when they do."/>}
      {has && (
        <div style={{display:'flex', flexDirection:'column', gap:10}}>
          {(full ? findings : findings.slice(0,2)).map(f => <FindingRow key={f.id} finding={f}/>)}
          {!full && findings.length > 2 && (
            <Btn kind="secondary" onClick={onOpenFindings}>View all {findings.length} findings →</Btn>
          )}
        </div>
      )}
    </div>
  );
}

function FindingRow({ finding }) {
  const sev = {
    major:       { bg:'#FEE2E2', bd:'#FCA5A5', fg:'#991B1B', label:'MAJOR' },
    minor:       { bg:'#FEF3C7', bd:'#FDE68A', fg:'#92400E', label:'MINOR' },
    observation: { bg:'#E8F4FC', bd:'#BAE0F7', fg:'#0C4A6E', label:'OBSERVATION' },
  }[finding.severity];
  return (
    <div style={{border:`1.5px solid ${sev.bd}`, background:sev.bg, borderRadius:10, padding:'14px 16px'}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', gap:10, marginBottom:6}}>
        <div style={{display:'flex', alignItems:'center', gap:10}}>
          <span style={{fontFamily:'JetBrains Mono, monospace', fontSize:10, fontWeight:800, color:sev.fg, letterSpacing:'0.06em', padding:'2px 6px', background:'rgba(255,255,255,0.6)', borderRadius:6}}>
            {finding.id} · {sev.label}
          </span>
          {finding.cap && <span style={{fontSize:10, fontWeight:800, color:'#7C5104', letterSpacing:'0.06em'}}>CAP · {finding.capDueDays}d</span>}
        </div>
        <span style={{fontSize:11, color:'#6B7280'}}>{finding.raised} · {finding.by}</span>
      </div>
      <div style={{fontSize:14, fontWeight:800, color:'#022C28', marginBottom:4}}>{finding.title}</div>
      <div style={{fontSize:12, color:'#4B5563', lineHeight:1.5}}>{finding.detail}</div>
    </div>
  );
}

function AuditTrailPreview({ project, full = false }) {
  const events = project.id === 'PRJ-KE-BUS001' ? HEDERA_EVENTS : syntheticEvents(project);
  const shown = full ? events : events.slice(0, 5);
  return (
    <div style={{background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, padding:24}}>
      <SectionHeader eyebrow="Trust" title="Hedera audit trail" tail="Live · read-only"/>
      <div style={{marginTop:14, display:'flex', flexDirection:'column', gap:0}}>
        {shown.map((e,i) => (
          <div key={i} style={{display:'flex', alignItems:'center', gap:14, padding:'10px 0', borderBottom:'1px dashed #F3F4F6'}}>
            <div style={{fontSize:11, color:'#9CA3AF', minWidth:120}}>{e.t}</div>
            <div style={{fontSize:12, fontWeight:700, color:'#022C28', minWidth:130}}>{e.actor}</div>
            <div style={{fontSize:12, color:'#4B5563', flex:1}}>{e.action}</div>
            <div style={{fontFamily:'JetBrains Mono, monospace', fontSize:10, color:'#7C5CFC'}}>{e.tx}</div>
          </div>
        ))}
      </div>
    </div>
  );
}
function syntheticEvents(project) {
  return [
    { t:'Today',  actor:'Grace K.',  action:`registered project ${project.id}`, tx:'0.0.8321350@103' },
    { t:'Today',  actor:'System',    action:'Phase 1 batch commit',             tx:'0.0.8321350@104' },
    { t:'Yesterday', actor:'Verra API', action:`imported methodology ${project.methodology}`, tx:'0.0.8321350@108' },
  ];
}

/* --- Sidebar cards ----------------------------------------- */
function ReadinessCard({ project }) {
  const tier = project.vvb >= 90 ? { label:'Validation-ready', color:'#059669' }
             : project.vvb >= 75 ? { label:'Nearly ready', color:'#059669' }
             : project.vvb >= 50 ? { label:'In progress', color:'#D97706' }
             :                     { label:'Early stage', color:'#9CA3AF' };
  return (
    <div style={{background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, padding:20}}>
      <div style={{fontSize:11, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:'#9CA3AF'}}>VVB Readiness</div>
      <div style={{fontSize:42, fontWeight:900, color:'#022C28', letterSpacing:'-0.02em', lineHeight:1, margin:'6px 0 4px'}}>
        {project.vvb}<span style={{fontSize:16, color:'#6B7280', fontWeight:600}}>/100</span>
      </div>
      <div style={{height:8, background:'#F3F4F6', borderRadius:9999, overflow:'hidden', marginTop:6}}>
        <div style={{height:'100%', background: project.vvb>=75 ? '#2BC48A' : project.vvb>=50 ? '#F4C300' : '#9CA3AF', width:`${project.vvb}%`}}/>
      </div>
      <div style={{fontSize:12, fontWeight:800, color:tier.color, marginTop:10}}>{tier.label}</div>
      <div style={{fontSize:11, color:'#6B7280', marginTop:4, lineHeight:1.5}}>
        Weighted P1 20% · P2 25% · P3 25% · P4 20% · P5 10%
      </div>
    </div>
  );
}

function CreditsCard({ project }) {
  const issued = project.credits;
  return (
    <div style={{background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, padding:20}}>
      <div style={{fontSize:11, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:'#9CA3AF', marginBottom:10}}>Credits</div>
      {issued > 0 ? (
        <>
          <Row k="Total issued"  v={issued.toLocaleString()} bold/>
          <Row k="Available"     v={project.available.toLocaleString()} fg="#B8960A"/>
          <Row k="Retired"       v={(issued - project.available).toLocaleString()}/>
        </>
      ) : (
        <>
          <Row k="Issued so far" v="0" muted/>
          <Row k="Projected (lifecycle)" v={project.projected.toLocaleString()} fg="#B8960A"/>
          <div style={{fontSize:11, color:'#6B7280', marginTop:10, lineHeight:1.5}}>
            Credits become issuable after Phase 5 sign-off. Estimate based on baseline × project area.
          </div>
        </>
      )}
    </div>
  );
}
function Row({ k, v, bold, fg, muted }) {
  return (
    <div style={{display:'flex', justifyContent:'space-between', marginBottom:8}}>
      <span style={{fontSize:12, color:'#6B7280'}}>{k}</span>
      <span style={{fontSize:13, fontWeight:800, color: fg || (muted ? '#9CA3AF' : '#022C28')}}>{v}</span>
    </div>
  );
}

function ProjectMetaCard({ project, expanded = false }) {
  return (
    <div style={{background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, padding:20}}>
      <div style={{fontSize:11, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:'#9CA3AF', marginBottom:10}}>Project</div>
      <Row k="Methodology"   v={project.methodology}/>
      <Row k="Location"      v={project.location}/>
      <Row k="Coordinates"   v={<span style={{fontFamily:'JetBrains Mono, monospace', fontSize:11}}>{project.coords}</span>}/>
      <Row k="Project area"  v={project.area}/>
      <Row k="Households"    v={project.households.toLocaleString()}/>
      {expanded && (
        <>
          <Row k="Species"        v={project.species}/>
          <Row k="Documents"      v={project.documents}/>
          <Row k="Plots"          v={`${project.plots}${project.plotsFlagged ? ` (${project.plotsFlagged} flagged)` : ''}`}/>
        </>
      )}
      <div style={{marginTop:10, paddingTop:10, borderTop:'1px dashed #F3F4F6'}}>
        <Row k="Assigned VVB" v={project.vvbAssigned ? project.vvbAssigned.firm : <span style={{color:'#9CA3AF'}}>Not assigned</span>}/>
        {project.vvbAssigned && <Row k="VVB lead" v={project.vvbAssigned.name}/>}
        {project.auditId && <Row k="Audit ID" v={<span style={{fontFamily:'JetBrains Mono, monospace', fontSize:11}}>{project.auditId}</span>}/>}
      </div>
    </div>
  );
}

function CreditsExpanded({ project }) {
  return (
    <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:20}}>
      <CreditsCard project={project}/>
      <div style={{background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, padding:20}}>
        <div style={{fontSize:11, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:'#9CA3AF', marginBottom:14}}>Issuance forecast</div>
        {project.credits > 0 ? (
          <>
            <div style={{fontSize:13, color:'#022C28', marginBottom:8}}>Next vintage: <b>Q3 2026</b></div>
            <div style={{fontSize:13, color:'#022C28', marginBottom:8}}>Expected: <b>{Math.round(project.projected * 0.15).toLocaleString()} tCO2e</b></div>
            <div style={{fontSize:11, color:'#6B7280'}}>Based on monitoring report ingestion cadence.</div>
          </>
        ) : (
          <EmptyState icon="clock" title="Not yet issuable" body={`This project reaches Phase 5 after the current Phase ${project.phase} is validated and Phase 4 monitoring completes.`}/>
        )}
      </div>
    </div>
  );
}

/* ============================================================
 * Phase-3 Workspace (net-new)
 *
 * Editable Phase-3 fields. Saving a flagged/empty field moves it
 * to 'confirmed' in-session. Save & continue commits the batch.
 * Permission-restricted: VVB sign-off button is visibly disabled
 * with a tooltip — proving the role separation.
 * ============================================================ */

function Phase3Workspace({ project, layoutMode = 'workspace', onBack, onOpenFindings }) {
  // 'workspace' = full editable; 'view' = read-only relabel ("View project")
  const [fields, setFields] = React.useState(() =>
    (project.id === 'PRJ-KE-BUS001' ? PHASE3_FIELDS : syntheticFields(project)).map(f => ({...f}))
  );
  const [editingId, setEditingId] = React.useState(null);
  const [draftValue, setDraftValue] = React.useState('');
  const [savedToast, setSavedToast] = React.useState(null);

  const stats = React.useMemo(() => {
    const c = fields.reduce((acc,f) => { acc[f.state] = (acc[f.state]||0)+1; return acc; }, {});
    const confirmed = (c.confirmed||0) + (c.committed||0) + (c.imported||0);
    return { confirmed, total: fields.length, empty: c.empty||0, flagged: c.flagged||0, ai: c.ai||0 };
  }, [fields]);

  const pct = Math.round((stats.confirmed / stats.total) * 100);

  const acceptAi = (id) => {
    setFields(fs => fs.map(f => f.id===id ? {...f, state:'confirmed', who:'Grace K. · just now'} : f));
    setSavedToast({ kind:'ai-accepted' });
    setTimeout(()=>setSavedToast(null), 2200);
  };
  const startEdit = (f) => { setEditingId(f.id); setDraftValue(f.state==='empty' ? '' : f.value); };
  const saveEdit = () => {
    setFields(fs => fs.map(f => f.id===editingId ? {...f, state:'confirmed', value: draftValue || f.value, who:'Grace K. · just now'} : f));
    setEditingId(null);
    setSavedToast({ kind:'saved' });
    setTimeout(()=>setSavedToast(null), 2200);
  };
  const resolveFlag = (id) => {
    setFields(fs => fs.map(f => f.id===id ? {...f, state:'confirmed', value: f.value + ' · justification attached', who:'Grace K. · just now'} : f));
    setSavedToast({ kind:'resolved' });
    setTimeout(()=>setSavedToast(null), 2200);
  };

  const isViewMode = layoutMode === 'view';

  return (
    <main style={{flex:1, padding:'28px 32px', background:'#F9FAFB', minWidth:0}}>
      <button onClick={onBack} style={{
        background:'transparent', border:'none', color:'#B8960A',
        fontSize:12, fontWeight:700, cursor:'pointer', padding:0, marginBottom:14,
        display:'inline-flex', alignItems:'center', gap:6, whiteSpace:'nowrap',
      }}>
        <PamojaIcon name="back" size={12} color="#B8960A" stroke={2.2}/>
        Back to project
      </button>

      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:24, marginBottom:20, flexWrap:'wrap'}}>
        <div>
          <div style={{fontFamily:'JetBrains Mono, monospace', fontSize:11, color:'#9CA3AF', marginBottom:4}}>{project.id} · Phase {project.phase}</div>
          <h1 style={{fontSize:26, fontWeight:900, color:'#022C28', letterSpacing:'-0.02em', margin:'0 0 10px'}}>
            {isViewMode ? `${project.name}` : `Phase ${project.phase} workspace`}
          </h1>
          <div style={{display:'flex', gap:8, alignItems:'center', flexWrap:'wrap'}}>
            <Badge variant={project.registryVariant} mono>{project.registry}</Badge>
            <Badge variant="gold">Phase {project.phase} · {project.phaseName}</Badge>
            <span style={{fontSize:12, color:'#6B7280'}}>· {project.methodology}</span>
          </div>
        </div>
        <div style={{display:'flex', gap:8, flexWrap:'wrap'}}>
          {!isViewMode && (
            <Btn kind="secondary" onClick={onOpenFindings} icon="flag">View VVB findings</Btn>
          )}
          {/* Permission-restricted: signing off is VVB-only */}
          <div title="Sign-off is a VVB action. Your role can view findings but cannot commit the validation verdict." style={{position:'relative'}}>
            <Btn kind="primary" disabled icon="lock">Sign & commit (VVB only)</Btn>
          </div>
        </div>
      </div>

      {/* Permission banner — proves the role separation */}
      <div style={{
        background:'#F3F4F6', border:'1px solid #E5E7EB', borderRadius:10, padding:'12px 16px',
        marginBottom:18, display:'flex', alignItems:'center', gap:12, fontSize:12, color:'#4B5563',
      }}>
        <PamojaIcon name="lock" size={14} color="#6B7280" stroke={1.7}/>
        <div>
          <b style={{color:'#022C28'}}>You're the project developer.</b>
          {' '}You can edit fields, accept AI suggestions, and respond to findings.
          Sampling, anomaly adjudication, and validation sign-off are VVB actions assigned to <b>{project.vvbAssigned?.name || 'an unassigned VVB'}</b>.
        </div>
      </div>

      {/* Progress strip */}
      <div style={{background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, padding:18, marginBottom:18, display:'flex', alignItems:'center', gap:24, flexWrap:'wrap'}}>
        <div style={{flex:1, minWidth:240}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:6, gap:12}}>
            <span style={{fontSize:12, fontWeight:700, color:'#022C28', whiteSpace:'nowrap'}}>Phase {project.phase} progress</span>
            <span style={{fontSize:13, fontWeight:900, color:'#022C28', whiteSpace:'nowrap', fontFamily:'JetBrains Mono, monospace'}}>{stats.confirmed}/{stats.total} · {pct}%</span>
          </div>
          <div style={{height:8, background:'#F3F4F6', borderRadius:9999, overflow:'hidden'}}>
            <div style={{height:'100%', background: pct>=80 ? '#2BC48A' : '#F4C300', width:`${pct}%`, transition:'width 400ms'}}/>
          </div>
        </div>
        <div style={{display:'flex', gap:20, flexShrink:0, flexWrap:'wrap'}}>
          <Stat l="Confirmed" v={stats.confirmed} c="#059669"/>
          <Stat l="AI sugg." v={stats.ai} c="#0077B6"/>
          <Stat l="Flagged" v={stats.flagged} c="#D97706"/>
          <Stat l="Empty" v={stats.empty} c="#9CA3AF"/>
        </div>
      </div>

      {/* Field grid */}
      <div style={{background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, padding:24}}>
        <SectionHeader eyebrow="Validation fields" title="Phase 3 — Project design document" tail={`${fields.length} fields · VM0047 §3-§6`}/>
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginTop:14}}>
          {fields.map(f => (
            <EditableField key={f.id} field={f}
              isEditing={editingId===f.id}
              draftValue={draftValue}
              setDraftValue={setDraftValue}
              onStartEdit={()=>startEdit(f)}
              onCancel={()=>setEditingId(null)}
              onSave={saveEdit}
              onAcceptAi={()=>acceptAi(f.id)}
              onResolve={()=>resolveFlag(f.id)}
              readOnly={isViewMode}
            />
          ))}
        </div>
      </div>

      {/* Save & continue */}
      {!isViewMode && (
        <div style={{
          marginTop:18, background:'#022C28', borderRadius:10, padding:'18px 24px',
          display:'flex', alignItems:'center', justifyContent:'space-between', gap:18,
          color:'#fff', flexWrap:'wrap',
        }}>
          <div>
            <div style={{fontSize:11, fontWeight:800, letterSpacing:'0.12em', textTransform:'uppercase', color:'#F4C300', marginBottom:4}}>Ready to commit</div>
            <div style={{fontSize:14, lineHeight:1.5, color:'rgba(255,255,255,0.85)'}}>
              Saving will batch-commit {stats.confirmed} fields to Hedera as a single audit anchor. <b style={{color:'#fff'}}>{stats.empty + stats.ai + stats.flagged} fields</b> still need attention before Phase {project.phase} can be sealed.
            </div>
          </div>
          <Btn kind="primary" icon="arrowRight">Save & continue</Btn>
        </div>
      )}

      {/* Toast */}
      {savedToast && (
        <div style={{
          position:'fixed', bottom:24, right:24, background:'#022C28', color:'#fff',
          padding:'14px 20px', borderRadius:10, boxShadow:'0 10px 30px rgba(0,0,0,0.2)',
          fontSize:13, fontWeight:700, display:'flex', alignItems:'center', gap:10, zIndex:200,
          animation:'p-pop 240ms ease-out',
        }}>
          <PamojaIcon name="check" size={16} color="#2BC48A" stroke={2.5}/>
          {savedToast.kind==='ai-accepted' && 'AI suggestion accepted — field confirmed.'}
          {savedToast.kind==='saved' && 'Field saved — staged for next commit.'}
          {savedToast.kind==='resolved' && 'Flag resolved with justification.'}
        </div>
      )}
    </main>
  );
}

function Stat({ l, v, c }) {
  return (
    <div style={{minWidth:64}}>
      <div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.06em', color:'#9CA3AF', whiteSpace:'nowrap'}}>{l}</div>
      <div style={{fontSize:20, fontWeight:900, color:c, marginTop:2, letterSpacing:'-0.01em', lineHeight:1}}>{v}</div>
    </div>
  );
}

function EditableField({ field, isEditing, draftValue, setDraftValue, onStartEdit, onCancel, onSave, onAcceptAi, onResolve, readOnly }) {
  const S = FIELD_STATE[field.state] || FIELD_STATE.empty;

  if (isEditing) {
    return (
      <div style={{border:`1.5px solid #F4C300`, background:'#FFF8E0', borderRadius:10, padding:'12px 14px'}}>
        <div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.08em', color:'#92400E', marginBottom:6}}>{field.label} · EDITING</div>
        <input autoFocus value={draftValue} onChange={(e)=>setDraftValue(e.target.value)} placeholder="Enter value…" style={{
          width:'100%', padding:'8px 10px', border:'1.5px solid #F4C300', borderRadius:8,
          fontSize:13, fontFamily:'inherit', outline:'none', marginBottom:10,
        }}/>
        <div style={{display:'flex', gap:8, justifyContent:'flex-end'}}>
          <button onClick={onCancel} style={{...btnSecondary, minHeight:32, padding:'4px 12px', fontSize:11}}>Cancel</button>
          <button onClick={onSave} style={{...btnPrimary, minHeight:32, padding:'4px 12px', fontSize:11}}>Save field</button>
        </div>
      </div>
    );
  }

  return (
    <div style={{border:`1.5px solid ${S.bd}`, background:S.bg, borderRadius:10, padding:'12px 14px', position:'relative'}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:5, gap:10}}>
        <div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.06em', color:S.lblc, lineHeight:1.3, flex:1, minWidth:0}}>{field.label}</div>
        <span style={{display:'inline-flex', alignItems:'center', gap:4, fontSize:9, fontWeight:800, color:S.lblc, letterSpacing:'0.04em', textTransform:'uppercase', whiteSpace:'nowrap', flexShrink:0, paddingTop:1}}>
          <PamojaIcon name={S.icon} size={10} color={S.lblc} stroke={2}/>
          {S.lbl}
        </span>
      </div>
      <div style={{fontSize:13, fontWeight:700, color:'#022C28', lineHeight:1.35, marginBottom:6}}>{field.value}</div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', gap:8, flexWrap:'wrap'}}>
        <span style={{fontSize:10, color:'#6B7280', letterSpacing:'0.02em'}}>{field.who}</span>
        {!readOnly && (
          <div style={{display:'flex', gap:6, flexShrink:0}}>
            {field.state==='ai' && <Pill onClick={onAcceptAi} color="#0077B6">Accept</Pill>}
            {field.state==='flagged' && <Pill onClick={onResolve} color="#D97706">Resolve</Pill>}
            {field.state==='empty' && <Pill onClick={onStartEdit} color="#022C28">Add value</Pill>}
            {(field.state==='confirmed'||field.state==='ai'||field.state==='flagged') && (
              <Pill onClick={onStartEdit} color="#6B7280" ghost>Edit</Pill>
            )}
            {field.state==='committed' && <span style={{fontSize:10, color:'#7C5CFC', fontWeight:800, letterSpacing:'0.04em'}}>SEALED</span>}
            {field.state==='imported' && <Pill onClick={onStartEdit} color="#0F766E" ghost>Override</Pill>}
          </div>
        )}
      </div>
    </div>
  );
}
function Pill({ children, onClick, color, ghost }) {
  return (
    <button onClick={onClick} style={{
      background: ghost ? 'transparent' : color,
      color: ghost ? color : '#fff',
      border: ghost ? `1px solid ${color}40` : 'none',
      fontFamily:'inherit', fontSize:10, fontWeight:800,
      padding:'4px 10px', borderRadius:9999, cursor:'pointer',
      letterSpacing:'0.04em', textTransform:'uppercase', whiteSpace:'nowrap',
    }}>{children}</button>
  );
}

window.ProjectDetail = ProjectDetail;
window.Phase3Workspace = Phase3Workspace;
