// Submission — one card. Form is always editable. Gate is only at submit.
const FORM_FIELDS = [
  { n: 1, ttl: 'Name of offer', pillar: '01', type: 'text', placeholder: 'e.g. CRM Suite' },
  { n: 2, ttl: 'The one problem it solves', pillar: '01', type: 'textarea', placeholder: 'When [trigger], my [customer] loses [outcome]. No "and".' },
  { n: 3, ttl: "Who it's for (shorthand)", pillar: '01', type: 'text', placeholder: 'e.g. US home-services agencies, 5–50 employees' },
  { n: 4, ttl: "Describe who it's for", pillar: '01', type: 'textarea', placeholder: 'Short avatar paragraph...' },
  { n: 5, ttl: 'Build walkthrough video', pillar: '05', type: 'file', hint: 'Shows the runbook end to end.' },
  { n: 6, ttl: 'Mock launch call video', pillar: '04', type: 'file', hint: 'Under 20:00. Shows the value working with test data, ends with the yes and go-live plan.' },
  { n: 7, ttl: 'Intake inputs list', pillar: '04', type: 'textarea', placeholder: 'List each input. Added time under 10 min, on top of the existing tech intake.' },
  { n: 8, ttl: 'Describe the ascension hook', pillar: '03', type: 'textarea', placeholder: 'Once problem #1 is solved, what problem becomes visible or unavoidable?' },
  { n: 9, ttl: 'Per-customer prep (human steps, before launch)', pillar: '05', type: 'textarea', placeholder: 'Step 1: ... (10 min)\nStep 2: ... (15 min) — under 3 human-hours total' },
];

function isFilled(v, type) {
  if (type === 'file') return !!v;
  return typeof v === 'string' && v.trim().length > 0;
}

function Submission({ checks }) {
  const [promise, setPromise] = React.useState(false);
  const [vals, setVals] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);

  const pillars = window.PILLARS;
  const totalChecks = checks.flat().length;
  const doneChecks = checks.flat().filter(Boolean).length;
  const allPass = doneChecks === totalChecks;
  const filled = FORM_FIELDS.filter(f => isFilled(vals[f.n], f.type)).length;
  const total = FORM_FIELDS.length;
  const canSubmit = allPass && promise && filled === total;

  if (submitted) {
    return (
      <section id="submission" className="submission-section">
        <div className="container-narrow">
          <div className="sub-success">
            <div className="sub-success-icon"><i className="fas fa-paper-plane"></i></div>
            <div className="sub-success-eye">Packet submitted</div>
            <h2 className="sub-success-h">Sent to Extendly fulfillment.</h2>
            <p>You'll hear back within one business day — pass, bounce with notes, or pass with caveats.</p>
            <button onClick={() => setSubmitted(false)} className="btn" style={{background:'rgba(255,255,255,0.08)',color:'white',border:'1px solid rgba(255,255,255,0.18)',padding:'10px 20px',fontSize:13.5,marginTop:18}}>
              <i className="fas fa-rotate-left"></i> Submit another
            </button>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section id="submission" className="submission-section">
      <div className="container-narrow">
        <div className="numchip" style={{marginBottom:16}}>
          <span className="dot" style={{background:'var(--ext-grad-secondary)'}}><i className="fas fa-paper-plane" style={{fontSize:10}}></i></span>
          <span>The submission packet</span>
        </div>
        <h2 className="page-h2">Submit your packet.</h2>
        <p className="page-lead" style={{marginTop:8,marginBottom:32}}>
          Nine fields. Fill them as you watch the videos above. Submit when every pillar is passing and the promise is acknowledged.
        </p>

        <div className="sub-card">
          {/* Readiness summary */}
          <div className="sub-readiness">
            <div className="sub-readiness-row">
              <span style={{fontFamily:'var(--font-headline)',fontWeight:800,fontSize:13,letterSpacing:'0.08em',textTransform:'uppercase',color:'var(--fg-3)'}}>Readiness</span>
              <span style={{fontFamily:'var(--font-mono)',fontSize:12,color:'var(--fg-2)'}}>{doneChecks}/{totalChecks} pillar checks · {filled}/{total} fields · {promise ? '✓' : '·'} promise</span>
            </div>
            <div className="sub-readiness-dots">
              {pillars.map((p, i) => {
                const d = checks[i].filter(Boolean).length;
                const t = checks[i].length;
                const ok = d === t;
                return (
                  <div key={p.n} className={`sub-dot ${ok ? 'on' : ''}`} title={`Pillar ${p.n} — ${d}/${t}`} style={ok ? {background: p.accent, borderColor: p.accent} : {}}>
                    <span>{p.n}</span>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Master promise */}
          <label className={`master-promise ${promise ? 'on' : ''}`} onClick={() => setPromise(!promise)}>
            <span className="master-box">
              {promise && <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>}
            </span>
            <span>
              <span className="master-eye">The master promise</span>
              <span className="master-txt">Your customer sees the result by the launch call, within 72 hours of the tech onboarding call.</span>
            </span>
          </label>

          {/* Form fields */}
          <div className="form-fields">
            {FORM_FIELDS.map(f => (
              <FormField
                key={f.n}
                field={f}
                value={vals[f.n]}
                onChange={(v) => setVals(prev => ({...prev, [f.n]: v}))}
              />
            ))}
          </div>

          {/* Submit */}
          <button
            disabled={!canSubmit}
            onClick={() => canSubmit && setSubmitted(true)}
            className="btn btn-primary submit-btn"
            style={{opacity: canSubmit ? 1 : 0.4, cursor: canSubmit ? 'pointer' : 'not-allowed'}}
          >
            <i className={`fas ${canSubmit ? 'fa-paper-plane' : 'fa-lock'}`}></i>
            {canSubmit ? 'Submit to Extendly' : <BlockerText doneChecks={doneChecks} totalChecks={totalChecks} promise={promise} filled={filled} total={total} />}
          </button>
        </div>
      </div>
    </section>
  );
}

function BlockerText({ doneChecks, totalChecks, promise, filled, total }) {
  if (doneChecks < totalChecks) return <>Tick {totalChecks - doneChecks} more pillar check{totalChecks - doneChecks === 1 ? '' : 's'} above</>;
  if (!promise) return <>Acknowledge the master promise</>;
  if (filled < total) return <>Fill {total - filled} more field{total - filled === 1 ? '' : 's'}</>;
  return <>Locked</>;
}

function FormField({ field, value, onChange }) {
  const pillar = window.PILLARS.find(p => p.n === field.pillar);
  return (
    <div className="ff">
      <div className="ff-head">
        <span className="ff-num">{String(field.n).padStart(2,'0')}</span>
        <div style={{flex:1,minWidth:0}}>
          <div className="ff-ttl">{field.ttl}</div>
          {field.hint && <div className="ff-hint">{field.hint}</div>}
        </div>
        <span className="ff-pillar" style={{background: pillar.accentTint, color: pillar.accentDark}}>Pillar {field.pillar}</span>
      </div>
      <FieldInput field={field} value={value} onChange={onChange} />
    </div>
  );
}

function FieldInput({ field, value, onChange }) {
  if (field.type === 'textarea') {
    return (
      <textarea
        value={value || ''}
        onChange={(e) => onChange(e.target.value)}
        placeholder={field.placeholder}
        rows={field.n === 9 ? 4 : 3}
        className="ff-input"
        style={{resize:'vertical',lineHeight:1.5}}
      />
    );
  }
  if (field.type === 'file') {
    const has = !!value;
    return (
      <label className={`ff-file ${has ? 'has' : ''}`}>
        <input type="file" accept="video/*" style={{display:'none'}} onChange={(e) => { const f = e.target.files?.[0]; if (f) onChange(f.name); }} />
        <span className="ff-file-icon"><i className={`fas ${has ? 'fa-check' : 'fa-cloud-arrow-up'}`}></i></span>
        <span>
          <span style={{fontWeight:700,fontSize:13.5,color:'var(--fg-1)'}}>{has ? value : 'Upload video file'}</span>
          <span style={{fontSize:11.5,color:'var(--fg-3)',display:'block',marginTop:1}}>{has ? 'Click to replace' : 'MP4 / MOV'}</span>
        </span>
      </label>
    );
  }
  return (
    <input
      type="text"
      value={value || ''}
      onChange={(e) => onChange(e.target.value)}
      placeholder={field.placeholder}
      className="ff-input"
    />
  );
}

window.Submission = Submission;
