/* Storyboard — scene cards w/ treatment swap, reorder, remove. window.Storyboard */
const { useState: useStateSB } = React;

const DEFAULT_PAYLOAD = {
  text:      { lines:[{t:'Your line',role:'hook',accent:true}] },
  bars:      { title:'Comparison', a:{label:'Then',val:'18 mo',pct:100}, b:{label:'Now',val:'2.4 wk',pct:14} },
  counter:   { value:'2.4', unit:'weeks', caption:'the new number' },
  ring:      { pct:72, caption:'of teams' },
  checklist: { items:['Faster','Cheaper','Copyable'] },
  quote:     { text:'Anyone can copy it.' },
  timeline:  { a:{val:'Then',label:'18 mo'}, b:{val:'Now',label:'2.4 wk'} },
  iconrow:   { items:[['⚡','Fast'],['💸','Cheap'],['🧬','Copyable']] },
};
window.DEFAULT_PAYLOAD = DEFAULT_PAYLOAD;

function FamilyDot({ family }) {
  return <span className="w-1.5 h-1.5 rounded-full" style={{ background: family==='say' ? '#FFE600' : '#2FA37C' }}/>;
}

function TreatmentPicker({ K, current, onPick, onClose }) {
  const I = window.Icon;
  const say = K.TREATMENT_ORDER.filter(id=>K.TREATMENTS[id].family==='say');
  const show = K.TREATMENT_ORDER.filter(id=>K.TREATMENTS[id].family==='show');
  const Group = ({ title, ids, family }) => (
    <div>
      <div className="flex items-center gap-2 px-1 mb-2">
        <FamilyDot family={family}/>
        <span className="text-[11px] font-semibold uppercase tracking-wide text-muted">{title}</span>
        <span className="text-[11px] text-faint">{family==='say'?'words hit':'proof'}</span>
      </div>
      <div className="grid grid-cols-2 gap-2">
        {ids.map(id=>{ const tr=K.TREATMENTS[id]; const sel=id===current;
          return (
            <button key={id} onClick={()=>onPick(id)} className={`flex items-center gap-2.5 p-2.5 rounded-xl border text-left transition-all ${sel?'border-accent bg-accent/[0.07]':'border-border bg-hi/40 hover:bg-hi hover:border-borders'}`}>
              <span className={`w-8 h-8 rounded-lg grid place-items-center shrink-0 ${sel?'bg-accent text-black':'bg-surface text-muted'}`}><tr.Icon size={16}/></span>
              <span className="min-w-0">
                <span className={`block text-[13px] font-medium truncate ${sel?'text-text':'text-text'}`}>{tr.label}</span>
                <span className="block text-[11px] text-faint truncate">{tr.blurb}</span>
              </span>
            </button>
          ); })}
      </div>
    </div>
  );
  return (
    <div className="mt-3 rounded-xl border border-border bg-surface/60 p-3 anim-floatup flex flex-col gap-4">
      <div className="flex items-center justify-between">
        <span className="text-[12px] font-semibold">Swap treatment</span>
        <button onClick={onClose} className="text-faint hover:text-text p-1 -mr-1"><I.X size={15}/></button>
      </div>
      <Group title="Say it" ids={say} family="say"/>
      <Group title="Show it" ids={show} family="show"/>
    </div>
  );
}

function SceneCard({ K, scene, idx, total, style, onSwap, onMove, onRemove }) {
  const I = window.Icon;
  const [picker, setPicker] = useStateSB(false);
  const tr = K.TREATMENTS[scene.treatment];
  const fam = tr.family==='say' ? 'Say it' : 'Show it';

  return (
    <div className="anim-popin rounded-2xl bg-surface border border-border p-3 sm:p-3.5">
      {/* header */}
      <div className="flex items-center gap-2.5">
        <span className="shrink-0 w-7 h-7 rounded-lg grid place-items-center bg-hi font-mono text-[12px] font-semibold text-muted tnum">{String(idx+1).padStart(2,'0')}</span>
        <span className="text-[11px] font-semibold uppercase tracking-wide text-faint">{scene.role}</span>
        <div className="ml-auto flex items-center gap-1">
          <button onClick={()=>onMove(idx,-1)} disabled={idx===0} className="w-8 h-8 rounded-lg grid place-items-center text-muted hover:text-text hover:bg-hi disabled:opacity-25 disabled:hover:bg-transparent transition-colors"><I.ChevronUp size={16}/></button>
          <button onClick={()=>onMove(idx,1)} disabled={idx===total-1} className="w-8 h-8 rounded-lg grid place-items-center text-muted hover:text-text hover:bg-hi disabled:opacity-25 disabled:hover:bg-transparent transition-colors"><I.ChevronDown size={16}/></button>
          <button onClick={()=>onRemove(idx)} disabled={total<=1} className="w-8 h-8 rounded-lg grid place-items-center text-muted hover:text-alert hover:bg-alert/10 disabled:opacity-25 disabled:hover:bg-transparent transition-colors"><I.Trash size={15}/></button>
        </div>
      </div>

      {/* body */}
      <div className="flex gap-3 mt-3">
        <div className="w-[58px] sm:w-16 shrink-0"><window.MiniTreatment scene={scene} style={style}/></div>
        <div className="flex-1 min-w-0 flex flex-col">
          <p className="text-[14.5px] sm:text-[15px] leading-snug text-text/90">{scene.text}</p>
          <button onClick={()=>setPicker(p=>!p)} className={`mt-2.5 self-start inline-flex items-center gap-2 pl-1.5 pr-2.5 py-1.5 rounded-lg border text-[12.5px] font-medium transition-colors ${picker?'border-accent text-text bg-accent/[0.06]':'border-border bg-hi/50 text-muted hover:text-text hover:border-borders'}`}>
            <span className="w-6 h-6 rounded-md grid place-items-center bg-surface"><tr.Icon size={14}/></span>
            <span className="flex items-center gap-1.5"><FamilyDot family={tr.family}/> {fam} · {tr.label}</span>
            <I.ChevronDown size={14} className={`transition-transform ${picker?'rotate-180':''}`}/>
          </button>
        </div>
      </div>

      {picker && <TreatmentPicker K={K} current={scene.treatment} onClose={()=>setPicker(false)} onPick={(id)=>{ onSwap(idx,id); setPicker(false); }}/>}
    </div>
  );
}

function Storyboard({ K, scenes, style, onSwap, onMove, onRemove, onAdd }) {
  const I = window.Icon;
  return (
    <div className="flex flex-col gap-5">
      <div className="anim-floatup">
        <div className="flex items-center gap-2 text-[11px] font-semibold tracking-[0.14em] text-muted uppercase mb-2">
          <I.Layers size={13}/> Storyboard
        </div>
        <h1 className="text-[24px] sm:text-[27px] leading-[1.08] font-bold tracking-tight">{scenes.length} scenes, one per beat.</h1>
        <p className="text-[13.5px] text-muted mt-2 leading-relaxed">Each beat gets a treatment. Swap, reorder, or cut any of them.</p>
      </div>

      {/* legend */}
      <div className="anim-floatup grid grid-cols-2 gap-2.5" style={{ animationDelay:'.04s' }}>
        <div className="rounded-xl bg-surface border border-border p-3">
          <div className="flex items-center gap-2 mb-1"><FamilyDot family="say"/><span className="text-[12.5px] font-semibold">Say it</span></div>
          <p className="text-[11.5px] text-muted leading-snug">Words hit — animated text.</p>
        </div>
        <div className="rounded-xl bg-surface border border-border p-3">
          <div className="flex items-center gap-2 mb-1"><FamilyDot family="show"/><span className="text-[12.5px] font-semibold">Show it</span></div>
          <p className="text-[11.5px] text-muted leading-snug">Proof — charts, lists, numbers.</p>
        </div>
      </div>

      {/* cards */}
      <div className="flex flex-col gap-3">
        {scenes.map((sc,i)=>(
          <SceneCard key={sc.id} K={K} scene={sc} idx={i} total={scenes.length} style={style} onSwap={onSwap} onMove={onMove} onRemove={onRemove}/>
        ))}
      </div>

      <button onClick={onAdd} className="anim-floatup self-stretch rounded-xl border border-dashed border-borders hover:border-faint py-3 flex items-center justify-center gap-2 text-[13px] text-muted hover:text-text transition-colors">
        <I.Plus size={16}/> Add a scene
      </button>
    </div>
  );
}

window.Storyboard = Storyboard;
