/* ============================================================
 * Create Project — three layout variants exposed via Tweaks:
 *   - 'stepper'  (default): 4-step wizard
 *   - 'single'   : one long form, validate on submit
 *   - 'sidepanel': slide-in panel from the right
 *
 * On submit, the new project is appended to the in-session list
 * and the parent opens its Phase-1 view.
 * ============================================================ */

const COUNTRIES = ['Kenya','Uganda','Tanzania','Rwanda','DR Congo','Malawi','Ethiopia','South Africa','Zambia','Mozambique'];
const METHODOLOGIES = [
  { id:'VM0047', name:'VM0047 v1.1', label:'Afforestation, Reforestation & Revegetation (Verra)', registry:'VERRA',        registryVariant:'verra' },
  { id:'VM0007', name:'VM0007 v3.0', label:'REDD+ Methodology Framework (Verra)',                  registry:'VERRA',        registryVariant:'verra' },
  { id:'ACM0022',name:'ACM0022 v1.0',label:'Avoided urban deforestation (Verra)',                  registry:'VERRA',        registryVariant:'verra' },
  { id:'PURO',   name:'Puro CORC 2024', label:'Biochar carbon removal (Puro.Earth)',                registry:'PURO',         registryVariant:'puro' },
  { id:'TPDDTEC',name:'TPDDTEC v4.0', label:'Improved cookstove technologies (Gold Standard)',     registry:'GOLDSTANDARD', registryVariant:'gold' },
  { id:'CAR',    name:'CAR Forest v5.0', label:'Avoided forest conversion (Climate Action Reserve)',registry:'CAR',         registryVariant:'gray' },
];

function CreateProjectFlow({ open, variant = 'stepper', onClose, onCreate }) {
  const [step, setStep] = React.useState(0);
  const [form, setForm] = React.useState({
    name:'', country:'Kenya', methodology:'VM0047', area:'', species:'', households:'',
  });
  React.useEffect(() => { if (open) { setStep(0); setForm({ name:'', country:'Kenya', methodology:'VM0047', area:'', species:'', households:'' }); } }, [open]);

  const setField = (k, v) => setForm(f => ({...f, [k]:v}));

  const submit = () => {
    const method = METHODOLOGIES.find(m=>m.id===form.methodology);
    const code = form.country.slice(0,2).toUpperCase();
    const suffix = String(Math.floor(Math.random() * 900) + 100);
    const newProject = {
      id: `PRJ-${code}-NEW${suffix}`,
      name: form.name || 'Untitled Project',
      location: `${form.country}`,
      coords: '—',
      methodology: method.name,
      methodologyName: method.label,
      registry: method.registry,
      registryVariant: method.registryVariant,
      phase: 1,
      phaseName: 'Eligibility',
      status: 'scoping',
      statusVariant: 'gray',
      area: form.area || '— (not set)',
      species: form.species || '—',
      households: Number(form.households) || 0,
      credits: 0,
      available: 0,
      projected: 0,
      vvb: 8,
      auditId: null,
      vvbAssigned: null,
      developer: { name:'Grace Kimani', org:'Pamoja EcoGreen Co-operative', email:'grace@ecogreen.co.ke' },
      findings: 0, findingsOpen: 0, capsOpen: 0,
      documents: 0, plots: 0, plotsFlagged: 0,
      phases: [
        { num:1, weight:20, name:'Eligibility', state:'current', detail:'0 of 7 fields · just created' },
        { num:2, weight:25, name:'PDD',         state:'todo',    detail:'Not started' },
        { num:3, weight:25, name:'Validation',  state:'todo',    detail:'Not started' },
        { num:4, weight:20, name:'Monitoring',  state:'todo',    detail:'Not started' },
        { num:5, weight:10, name:'Issuance',    state:'todo',    detail:'Not started' },
      ],
    };
    onCreate(newProject);
  };

  if (!open) return null;

  if (variant === 'sidepanel') return <CreateSidePanel open={open} onClose={onClose} form={form} setField={setField} onSubmit={submit}/>;
  if (variant === 'single')    return <CreateSingleModal open={open} onClose={onClose} form={form} setField={setField} onSubmit={submit}/>;
  return <CreateStepperModal open={open} onClose={onClose} step={step} setStep={setStep} form={form} setField={setField} onSubmit={submit}/>;
}

/* --- Variant 1: stepper (default) --------------------------- */
function CreateStepperModal({ open, onClose, step, setStep, form, setField, onSubmit }) {
  const steps = ['Basics', 'Methodology', 'Scope', 'Review'];
  const canAdvance = [
    () => form.name.trim().length > 2,
    () => !!form.methodology,
    () => true,
    () => true,
  ][step]();
  const last = step === steps.length - 1;
  return (
    <Modal open={open} onClose={onClose} width={720} padding={0}>
      <CreateHeader onClose={onClose}/>
      {/* Stepper */}
      <div style={{padding:'18px 32px 0', display:'flex', gap:0, borderBottom:'1px solid #F3F4F6'}}>
        {steps.map((s,i) => (
          <div key={s} style={{flex:1, paddingBottom:14, position:'relative'}}>
            <div style={{display:'flex', alignItems:'center', gap:8}}>
              <div style={{
                width:24, height:24, borderRadius:'50%',
                background: i<=step ? '#F4C300' : '#fff',
                border: i===step ? '2px solid #022C28' : i<step ? 'none' : '1.5px solid #E5E7EB',
                color: i<=step ? '#022C28' : '#9CA3AF',
                fontSize:11, fontWeight:900,
                display:'flex', alignItems:'center', justifyContent:'center',
              }}>{i<step ? '✓' : i+1}</div>
              <span style={{fontSize:12, fontWeight: i===step ? 800 : 700, color: i<=step ? '#022C28' : '#9CA3AF'}}>{s}</span>
            </div>
            {i===step && <div style={{position:'absolute', bottom:-1, left:0, right:0, height:2, background:'#F4C300'}}/>}
          </div>
        ))}
      </div>

      <div style={{padding:'24px 32px', minHeight:280}}>
        {step === 0 && <StepBasics form={form} setField={setField}/>}
        {step === 1 && <StepMethodology form={form} setField={setField}/>}
        {step === 2 && <StepScope form={form} setField={setField}/>}
        {step === 3 && <StepReview form={form}/>}
      </div>

      <div style={{padding:'18px 32px', borderTop:'1px solid #E5E7EB', display:'flex', justifyContent:'space-between', alignItems:'center', background:'#FAFAFA'}}>
        <button onClick={step===0 ? onClose : ()=>setStep(step-1)} style={{
          background:'transparent', border:'none', color:'#6B7280',
          fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'inherit',
        }}>{step===0 ? 'Cancel' : '← Back'}</button>
        <div style={{display:'flex', gap:10, alignItems:'center'}}>
          <span style={{fontSize:11, color:'#9CA3AF'}}>Step {step+1} of {steps.length}</span>
          {last
            ? <Btn kind="primary" onClick={onSubmit} icon="check">Create project</Btn>
            : <Btn kind="primary" disabled={!canAdvance} onClick={()=>setStep(step+1)} icon="arrowRight">Continue</Btn>
          }
        </div>
      </div>
    </Modal>
  );
}

/* --- Variant 2: single-page modal --------------------------- */
function CreateSingleModal({ open, onClose, form, setField, onSubmit }) {
  return (
    <Modal open={open} onClose={onClose} width={720} padding={0}>
      <CreateHeader onClose={onClose}/>
      <div style={{padding:'24px 32px', maxHeight:'70vh', overflow:'auto'}}>
        <StepBasics form={form} setField={setField}/>
        <hr style={{border:'none', borderTop:'1px dashed #E5E7EB', margin:'24px 0'}}/>
        <StepMethodology form={form} setField={setField}/>
        <hr style={{border:'none', borderTop:'1px dashed #E5E7EB', margin:'24px 0'}}/>
        <StepScope form={form} setField={setField}/>
      </div>
      <div style={{padding:'18px 32px', borderTop:'1px solid #E5E7EB', display:'flex', justifyContent:'flex-end', gap:10, background:'#FAFAFA'}}>
        <Btn kind="secondary" onClick={onClose}>Cancel</Btn>
        <Btn kind="primary" onClick={onSubmit} icon="check" disabled={form.name.trim().length < 3}>Create project</Btn>
      </div>
    </Modal>
  );
}

/* --- Variant 3: side panel ---------------------------------- */
function CreateSidePanel({ open, onClose, form, setField, onSubmit }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose && onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, background:'rgba(2,44,40,0.45)', zIndex:100,
      display:'flex', justifyContent:'flex-end',
      animation:'p-fade 200ms ease-out',
    }}>
      <div onClick={e=>e.stopPropagation()} style={{
        background:'#fff', width:520, maxWidth:'100%', height:'100vh',
        display:'flex', flexDirection:'column',
        boxShadow:'-12px 0 60px rgba(0,0,0,0.18)',
        animation:'p-slide 280ms ease-out',
      }}>
        <CreateHeader onClose={onClose} compact/>
        <div style={{padding:'24px 28px', flex:1, overflow:'auto'}}>
          <StepBasics form={form} setField={setField}/>
          <hr style={{border:'none', borderTop:'1px dashed #E5E7EB', margin:'24px 0'}}/>
          <StepMethodology form={form} setField={setField}/>
          <hr style={{border:'none', borderTop:'1px dashed #E5E7EB', margin:'24px 0'}}/>
          <StepScope form={form} setField={setField}/>
        </div>
        <div style={{padding:'16px 28px', borderTop:'1px solid #E5E7EB', display:'flex', justifyContent:'flex-end', gap:10, background:'#FAFAFA'}}>
          <Btn kind="secondary" onClick={onClose}>Cancel</Btn>
          <Btn kind="primary" onClick={onSubmit} icon="check" disabled={form.name.trim().length < 3}>Create project</Btn>
        </div>
      </div>
    </div>
  );
}

/* --- Shared header ----------------------------------------- */
function CreateHeader({ onClose, compact }) {
  return (
    <div style={{
      padding: compact ? '18px 28px' : '24px 32px',
      borderBottom:'1px solid #F3F4F6',
      display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:14,
    }}>
      <div>
        <div style={{fontSize:11, fontWeight:800, letterSpacing:'0.12em', textTransform:'uppercase', color:'#F4C300', marginBottom:4}}>Register project</div>
        <h2 style={{fontSize: compact ? 20 : 22, fontWeight:900, color:'#022C28', margin:0, letterSpacing:'-0.01em'}}>New carbon project</h2>
        <p style={{fontSize:12, color:'#6B7280', margin:'4px 0 0', maxWidth:480, lineHeight:1.5}}>Register the project to Pamoja. You'll be able to upload PDDs and complete Phase 1 fields after creation.</p>
      </div>
      <button onClick={onClose} style={{
        background:'transparent', border:'none', cursor:'pointer', padding:6, marginTop:-2,
      }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#9CA3AF" strokeWidth="2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </button>
    </div>
  );
}

/* --- Steps -------------------------------------------------- */
function StepBasics({ form, setField }) {
  return (
    <div>
      <SectionLabel title="Project basics" sub="The name and host country"/>
      <Field label="Project name" required>
        <input value={form.name} onChange={(e)=>setField('name', e.target.value)} placeholder="e.g. Kakamega Forest Reforestation" style={inp}/>
      </Field>
      <Field label="Host country" required>
        <select value={form.country} onChange={(e)=>setField('country', e.target.value)} style={inp}>
          {COUNTRIES.map(c => <option key={c}>{c}</option>)}
        </select>
      </Field>
    </div>
  );
}

function StepMethodology({ form, setField }) {
  return (
    <div>
      <SectionLabel title="Methodology &amp; registry" sub="Pamoja imports methodology metadata from the registry on selection"/>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10}}>
        {METHODOLOGIES.map(m => {
          const selected = form.methodology === m.id;
          return (
            <button key={m.id} onClick={()=>setField('methodology', m.id)} style={{
              textAlign:'left', cursor:'pointer', fontFamily:'inherit',
              padding:14, borderRadius:10,
              background: selected ? '#FFF8E0' : '#fff',
              border: selected ? '1.5px solid #F4C300' : '1.5px solid #E5E7EB',
              transition:'all 150ms',
            }}>
              <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:6}}>
                <span style={{fontFamily:'JetBrains Mono, monospace', fontSize:11, fontWeight:800, color:'#022C28', letterSpacing:'0.04em'}}>{m.name}</span>
                <Badge variant={m.registryVariant} mono>{m.registry}</Badge>
              </div>
              <div style={{fontSize:12, color:'#4B5563', lineHeight:1.45}}>{m.label}</div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function StepScope({ form, setField }) {
  return (
    <div>
      <SectionLabel title="Initial scope" sub="You can refine these in Phase 1 — leave blank if you don't have them yet"/>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:14}}>
        <Field label="Project area">
          <input value={form.area} onChange={(e)=>setField('area', e.target.value)} placeholder="e.g. 12,450 ha" style={inp}/>
        </Field>
        <Field label="Households participating">
          <input value={form.households} onChange={(e)=>setField('households', e.target.value)} placeholder="e.g. 1,800" style={inp}/>
        </Field>
      </div>
      <Field label="Species or activity mix">
        <input value={form.species} onChange={(e)=>setField('species', e.target.value)} placeholder="e.g. Bambusa vulgaris (60%), Oxytenanthera (40%)" style={inp}/>
      </Field>
    </div>
  );
}

function StepReview({ form }) {
  const method = METHODOLOGIES.find(m=>m.id===form.methodology);
  return (
    <div>
      <SectionLabel title="Review &amp; create" sub="The project will be created in Phase 1 — you can edit fields after"/>
      <div style={{background:'#F9FAFB', border:'1px solid #E5E7EB', borderRadius:10, padding:'18px 20px'}}>
        <ReviewRow k="Project name" v={form.name || <span style={{color:'#9CA3AF'}}>Not set</span>}/>
        <ReviewRow k="Country"      v={form.country}/>
        <ReviewRow k="Methodology"  v={<span>{method.name} <span style={{fontSize:11, color:'#6B7280'}}>· {method.label}</span></span>}/>
        <ReviewRow k="Registry"     v={<Badge variant={method.registryVariant} mono>{method.registry}</Badge>}/>
        <ReviewRow k="Area"         v={form.area || <span style={{color:'#9CA3AF'}}>—</span>}/>
        <ReviewRow k="Households"   v={form.households || <span style={{color:'#9CA3AF'}}>—</span>}/>
        <ReviewRow k="Species"      v={form.species || <span style={{color:'#9CA3AF'}}>—</span>} last/>
      </div>
      <div style={{marginTop:14, padding:'12px 14px', background:'#E6FBF3', border:'1px solid #A7F3D0', borderRadius:10, display:'flex', gap:10, alignItems:'flex-start'}}>
        <PamojaIcon name="check" size={16} color="#059669" stroke={2.2} style={{marginTop:1}}/>
        <div style={{fontSize:12, color:'#065F46', lineHeight:1.5}}>
          On create, the project will be assigned a new ID and registered on Hedera as <span style={{fontFamily:'JetBrains Mono, monospace', fontWeight:700}}>register</span>. You can invite field agents from the project page.
        </div>
      </div>
    </div>
  );
}

function SectionLabel({ title, sub }) {
  return (
    <div style={{marginBottom:14}}>
      <div style={{fontSize:15, fontWeight:900, color:'#022C28', letterSpacing:'-0.01em'}}>{title}</div>
      {sub && <div style={{fontSize:12, color:'#6B7280', marginTop:2}}>{sub}</div>}
    </div>
  );
}

function Field({ label, required, children }) {
  return (
    <div style={{marginBottom:14}}>
      <div style={{fontSize:11, fontWeight:800, color:'#022C28', marginBottom:6, letterSpacing:'0.02em'}}>
        {label} {required && <span style={{color:'#DC2626'}}>*</span>}
      </div>
      {children}
    </div>
  );
}

const inp = {
  width:'100%', padding:'11px 14px', border:'1.5px solid #E5E7EB', borderRadius:10,
  fontSize:14, fontFamily:'inherit', outline:'none', color:'#022C28',
  background:'#fff', minHeight:44,
  transition:'border-color 200ms, box-shadow 200ms',
};

function ReviewRow({ k, v, last }) {
  return (
    <div style={{display:'flex', justifyContent:'space-between', padding:'8px 0', borderBottom: last ? 'none' : '1px dashed #E5E7EB', alignItems:'center', gap:10}}>
      <span style={{fontSize:11, fontWeight:700, color:'#6B7280', letterSpacing:'0.04em', textTransform:'uppercase'}}>{k}</span>
      <span style={{fontSize:13, fontWeight:700, color:'#022C28', textAlign:'right'}}>{v}</span>
    </div>
  );
}

window.CreateProjectFlow = CreateProjectFlow;
