/* ============================================================
 * Developer · Dashboard + Projects list view.
 *
 * Fixes from the brief:
 *   - "+ New project" opens a real modal (handled by parent)
 *   - "Resume Phase 3" → opens the hero project's Phase-3 workspace
 *   - Project rows are click-to-detail (entire row)
 *   - Uses one canonical dataset (PROJECTS)
 * ============================================================ */

function DeveloperDashboard({ projects, hero, onOpenProject, onResumePhase3, onCreateProject, onOpenView }) {
  const portfolio = React.useMemo(() => {
    const issued = projects.reduce((s,p)=>s+p.credits, 0);
    const projected = projects.reduce((s,p)=>s+p.projected, 0);
    const avgVvb = Math.round(projects.reduce((s,p)=>s+p.vvb, 0)/projects.length);
    const registries = new Set(projects.map(p=>p.registry)).size;
    return { issued, projected, avgVvb, registries };
  }, [projects]);

  return (
    <main style={{flex:1, padding:'28px 32px', background:'#F9FAFB', minWidth:0}}>
      {/* Title row */}
      <div style={{marginBottom:24, display:'flex', justifyContent:'space-between', alignItems:'flex-end', gap:24, flexWrap:'wrap'}}>
        <div>
          <div style={{fontSize:11, fontWeight:800, letterSpacing:'0.12em', textTransform:'uppercase', color:'#F4C300', marginBottom:4}}>
            Developer Portal
          </div>
          <h1 style={{fontSize:32, fontWeight:900, color:'#022C28', letterSpacing:'-0.02em', margin:0, lineHeight:1.05}}>
            Karibu, Grace
          </h1>
          <p style={{fontSize:14, color:'#6B7280', margin:'6px 0 0'}}>
            {projects.length} projects across {portfolio.registries} registries · {portfolio.issued.toLocaleString()} tCO2e verified to date · {portfolio.projected.toLocaleString()} projected
          </p>
        </div>
        <div style={{display:'flex', gap:8}}>
          <Btn kind="secondary" icon="download">Export portfolio</Btn>
          <Btn kind="primary" icon="plus" onClick={onCreateProject}>New project</Btn>
        </div>
      </div>

      {/* Stat row */}
      <div style={{display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginBottom:24}}>
        <StatCard label="Total projects"  value={projects.length} sub={`${portfolio.registries} registries · 4 countries`} accent="#F4C300" icon="projects"/>
        <StatCard label="tCO2e verified"  value={portfolio.issued.toLocaleString()} sub="Anchored on Hedera testnet" accent="#2BC48A" icon="check"/>
        <StatCard label="VVB readiness"   value={portfolio.avgVvb}  sub="Portfolio average · weighted P1-5" accent="#0077B6" icon="shield"/>
        <StatCard label="Hedera anchors"  value="1,247" sub="Last commit 14m ago" accent="#7C5CFC" icon="hedera"/>
      </div>

      {/* Hero project — Continue working */}
      <div style={{background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, padding:24, marginBottom:24}}>
        <div style={{display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:14, gap:14}}>
          <div>
            <div style={{fontSize:11, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.12em', color:'#9CA3AF', marginBottom:2}}>
              Continue working
            </div>
            <div style={{display:'flex', alignItems:'center', gap:10}}>
              <h2 style={{fontSize:20, fontWeight:900, color:'#022C28', letterSpacing:'-0.01em', margin:0}}>{hero.name}</h2>
              <Badge variant={hero.registryVariant} mono>{hero.registry}</Badge>
              <Badge variant={hero.statusVariant} dot>{hero.status}</Badge>
            </div>
            <div style={{fontSize:12, color:'#6B7280', marginTop:4}}>
              <span style={{fontFamily:'JetBrains Mono, monospace'}}>{hero.id}</span> · {hero.location} · {hero.methodology}
            </div>
          </div>
          <div style={{textAlign:'right'}}>
            <div style={{fontSize:11, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.12em', color:'#9CA3AF'}}>VVB Readiness</div>
            <div style={{fontSize:24, fontWeight:900, color:'#022C28', letterSpacing:'-0.02em', lineHeight:1}}>
              {hero.vvb}<span style={{fontSize:13, color:'#6B7280', fontWeight:600}}>/100</span>
            </div>
            <div style={{fontSize:11, color:'#059669', fontWeight:800, marginTop:4}}>Nearly ready for validation</div>
          </div>
        </div>

        <PhaseTrackInline phases={hero.phases}/>

        <div style={{marginTop:18, paddingTop:18, borderTop:'1px dashed #E5E7EB', display:'flex', justifyContent:'space-between', alignItems:'center', gap:14, flexWrap:'wrap'}}>
          <div style={{fontSize:13, color:'#022C28', lineHeight:1.45}}>
            <b style={{color:'#92400E'}}>6 fields remaining</b> in Phase 3 · Resolve the DBH plot 42 outlier and upload tenure / FPIC docs to unlock submission.
            {hero.findingsOpen > 0 && (
              <> · <a href="#" onClick={(e)=>{e.preventDefault(); onOpenView('findings');}} style={{color:'#B8960A', fontWeight:700, textDecoration:'none'}}>{hero.findingsOpen} VVB findings open →</a></>
            )}
          </div>
          <div style={{display:'flex', gap:8}}>
            <Btn kind="secondary" onClick={()=>onOpenProject(hero)}>View project</Btn>
            <Btn kind="primary" onClick={()=>onResumePhase3(hero)} icon="arrowRight">Resume Phase 3</Btn>
          </div>
        </div>
      </div>

      {/* Projects table */}
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:12}}>
        <div>
          <div style={{fontSize:11, fontWeight:800, letterSpacing:'0.12em', textTransform:'uppercase', color:'#9CA3AF'}}>Projects</div>
          <h2 style={{fontSize:18, fontWeight:900, color:'#022C28', margin:'2px 0 0'}}>All projects</h2>
        </div>
        <div style={{display:'flex', gap:8}}>
          <input placeholder="Search projects, registries…" style={inputBase}/>
          <select style={{...inputBase, paddingRight:32}}>
            <option>All registries</option><option>Verra</option><option>Gold Standard</option><option>Puro</option><option>CAR</option>
          </select>
        </div>
      </div>
      <ProjectsTable projects={projects} onOpen={onOpenProject}/>

      <div style={{marginTop:20, padding:'14px 20px', background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, display:'flex', justifyContent:'space-between', alignItems:'center'}}>
        <div style={{display:'flex', alignItems:'center', gap:12}}>
          <div style={{width:10, height:10, borderRadius:'50%', background:'#2BC48A', boxShadow:'0 0 0 4px rgba(43,196,138,0.15)'}}/>
          <div>
            <div style={{fontSize:13, fontWeight:700, color:'#022C28'}}>Hedera testnet — operational</div>
            <div style={{fontSize:11, color:'#6B7280'}}>1,247 audit anchors · last commit <span style={{fontFamily:'JetBrains Mono, monospace'}}>0.0.8321350@142</span></div>
          </div>
        </div>
        <a href="#" onClick={(e)=>{e.preventDefault(); onOpenView('hedera');}} style={{color:'#B8960A', fontSize:12, fontWeight:700, textDecoration:'none', display:'inline-flex', alignItems:'center', gap:6}}>
          Hedera Monitor <PamojaIcon name="arrowRight" size={12} color="#B8960A" stroke={2.2}/>
        </a>
      </div>
    </main>
  );
}

/* --- Inline phase track (compact, dashboard hero variant) ---- */
function PhaseTrackInline({ phases }) {
  return (
    <div style={{display:'grid', gridTemplateColumns:'repeat(5,1fr)', gap:8}}>
      {phases.map((p,i)=> {
        const style = {
          done:    { bg:'#E6FBF3', bd:'#2BC48A', label:'#059669' },
          current: { bg:'#FFF8E0', bd:'#F4C300', label:'#92400E' },
          todo:    { bg:'#fff',    bd:'#E5E7EB', label:'#9CA3AF' },
        }[p.state];
        return (
          <div key={i} style={{background:style.bg, border:`1px solid ${style.bd}`, borderRadius:10, padding:'10px 12px'}}>
            <div style={{fontSize:9, textTransform:'uppercase', letterSpacing:'0.08em', color:style.label, fontWeight:800}}>
              Phase {p.num} · {p.weight}%
            </div>
            <div style={{fontSize:13, fontWeight:800, color:'#022C28', marginTop:3, display:'flex', alignItems:'center', gap:6}}>
              <span>{p.name}</span>
              {p.state==='done' && <PamojaIcon name="check" size={12} color="#059669" stroke={2.5}/>}
            </div>
            <div style={{fontSize:10, color:'#6B7280', marginTop:3}}>{p.detail}</div>
          </div>
        );
      })}
    </div>
  );
}

/* --- Whole-row clickable projects table ---------------------- */
function ProjectsTable({ projects, onOpen }) {
  return (
    <div style={{background:'#fff', border:'1px solid #E5E7EB', borderRadius:10, overflow:'hidden'}}>
      <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
        <thead>
          <tr style={{background:'#F9FAFB', borderBottom:'1px solid #E5E7EB'}}>
            <Th>Project</Th><Th>Registry</Th><Th>Phase</Th><Th>Status</Th>
            <Th align="right">Credits</Th><Th align="right">VVB</Th><Th></Th>
          </tr>
        </thead>
        <tbody>
          {projects.map(p => (
            <tr key={p.id} onClick={()=>onOpen(p)} style={{borderBottom:'1px solid #F3F4F6', cursor:'pointer', transition:'background 150ms'}}
                onMouseEnter={e=>e.currentTarget.style.background='#FFF8E0'}
                onMouseLeave={e=>e.currentTarget.style.background='#fff'}>
              <td style={tdStyle}>
                <div style={{fontWeight:800, color:'#022C28'}}>{p.name}</div>
                <div style={{display:'flex', gap:8, alignItems:'center', marginTop:2}}>
                  <span style={{fontFamily:'JetBrains Mono, monospace', fontSize:10, color:'#9CA3AF'}}>{p.id}</span>
                  <span style={{color:'#E5E7EB'}}>·</span>
                  <span style={{fontSize:11, color:'#6B7280'}}>{p.location}</span>
                </div>
              </td>
              <td style={tdStyle}><Badge variant={p.registryVariant} mono>{p.registry}</Badge></td>
              <td style={tdStyle}>
                <div style={{fontWeight:700, color:'#022C28'}}>Phase {p.phase}</div>
                <div style={{fontSize:11, color:'#6B7280'}}>{p.phaseName}</div>
              </td>
              <td style={tdStyle}><Badge variant={p.statusVariant} dot>{p.status}</Badge></td>
              <td style={{...tdStyle, textAlign:'right'}}>
                <div style={{fontWeight:800, color:'#022C28'}}>{p.credits ? p.credits.toLocaleString() : '—'}</div>
                <div style={{fontSize:11, color:'#B8960A'}}>{p.credits ? p.available.toLocaleString() + ' avail.' : `${p.projected.toLocaleString()} proj.`}</div>
              </td>
              <td style={{...tdStyle, textAlign:'right'}}>
                <div style={{fontWeight:800, color: p.vvb>=80?'#059669':p.vvb>=60?'#D97706':'#DC2626'}}>{p.vvb}</div>
                <div style={{fontSize:10, color:'#9CA3AF'}}>/100</div>
              </td>
              <td style={{...tdStyle, textAlign:'right', width:60}}>
                <PamojaIcon name="arrowRight" size={14} color="#9CA3AF" stroke={2}/>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

const tdStyle = { padding:'14px 16px', verticalAlign:'middle' };
function Th({ children, align='left' }) {
  return <th style={{
    textAlign:align, padding:'10px 16px',
    fontSize:10, fontWeight:800, letterSpacing:'0.1em', textTransform:'uppercase',
    color:'#9CA3AF',
  }}>{children}</th>;
}

const inputBase = {
  padding:'10px 14px', border:'1.5px solid #E5E7EB', borderRadius:10,
  fontSize:13, fontFamily:'inherit', minHeight:42, outline:'none',
  background:'#fff', color:'#022C28',
};

/* --- Projects-only view (Projects tab in sidebar) ------------ */
function ProjectsView({ projects, onOpen, onCreateProject }) {
  return (
    <main style={{flex:1, padding:'28px 32px', background:'#F9FAFB', minWidth:0}}>
      <div style={{marginBottom:24, display:'flex', justifyContent:'space-between', alignItems:'flex-end', gap:24}}>
        <div>
          <div style={{fontSize:11, fontWeight:800, letterSpacing:'0.12em', textTransform:'uppercase', color:'#F4C300', marginBottom:4}}>
            Developer Portal
          </div>
          <h1 style={{fontSize:28, fontWeight:900, color:'#022C28', letterSpacing:'-0.02em', margin:0, lineHeight:1.1}}>
            Projects
          </h1>
          <p style={{fontSize:14, color:'#6B7280', margin:'6px 0 0'}}>
            {projects.length} projects · click any row to open
          </p>
        </div>
        <Btn kind="primary" icon="plus" onClick={onCreateProject}>New project</Btn>
      </div>

      <div style={{display:'flex', gap:8, marginBottom:14, flexWrap:'wrap'}}>
        <input placeholder="Search projects, IDs, methodologies…" style={{...inputBase, flex:1, minWidth:280}}/>
        <select style={{...inputBase, paddingRight:32}}>
          <option>All registries</option><option>Verra</option><option>Gold Standard</option><option>Puro</option><option>CAR</option>
        </select>
        <select style={{...inputBase, paddingRight:32}}>
          <option>All phases</option><option>Phase 1</option><option>Phase 2</option><option>Phase 3</option><option>Phase 4</option><option>Phase 5</option>
        </select>
        <Btn kind="secondary" icon="filter">More filters</Btn>
      </div>

      <ProjectsTable projects={projects} onOpen={onOpen}/>
    </main>
  );
}

window.DeveloperDashboard = DeveloperDashboard;
window.ProjectsView = ProjectsView;
window.ProjectsTable = ProjectsTable;
window.PhaseTrackInline = PhaseTrackInline;
