/* Treatments — schematic mini-previews + big animated versions.
   window.MiniTreatment, window.BigTreatment */

const fontClassOf = (f) => ({ heavy:'font-heavy', serif:'font-serif', mono:'font-mono', sans:'font-sans' }[f] || 'font-sans');

/* ============ MINI (storyboard scene cards) — fits a ~58px square ============ */
function MiniTreatment({ scene, style }) {
  const s = style, p = scene.payload || {};
  const fc = fontClassOf(s.font);
  const box = {
    width: '100%', aspectRatio: '9/12', background: s.bg, borderRadius: 7,
    overflow: 'hidden', position: 'relative', display: 'flex',
    alignItems: 'center', justifyContent: 'center', padding: 5,
  };
  const t = scene.treatment;

  if (t === 'text') {
    return (
      <div style={box}>
        <div className="flex flex-col items-center text-center leading-none gap-[2px]">
          {(p.lines || []).slice(0,2).map((ln,i)=>(
            <span key={i} className={fc} style={{ fontSize: ln.role==='small'?5:9, fontWeight: s.weight,
              color: ln.accent? s.accent : s.text, textTransform: s.upper?'uppercase':'none',
              fontStyle: s.font==='serif'&&ln.accent?'italic':'normal', letterSpacing: s.tracking }}>{ln.t}</span>
          ))}
        </div>
      </div>
    );
  }
  if (t === 'bars') {
    return (
      <div style={box}>
        <div className="flex items-end gap-[5px] h-[64%]">
          <div className="w-[10px] rounded-sm" style={{ height:'100%', background:s.text, opacity:.32 }} />
          <div className="w-[10px] rounded-sm" style={{ height:`${Math.max(14,p.b?.pct||20)}%`, background:s.accent }} />
        </div>
      </div>
    );
  }
  if (t === 'counter') {
    return (
      <div style={box}>
        <div className="flex flex-col items-center leading-none">
          <span className={fc} style={{ fontSize:16, fontWeight:s.weight, color:s.accent }}>{p.value}</span>
          <span className={fc} style={{ fontSize:5, color:s.text, opacity:.7, marginTop:1 }}>{p.unit}</span>
        </div>
      </div>
    );
  }
  if (t === 'ring') {
    const pct = p.pct ?? 72, r=11, c=2*Math.PI*r;
    return (
      <div style={box}>
        <svg width="34" height="34" viewBox="0 0 34 34" className="-rotate-90">
          <circle cx="17" cy="17" r={r} fill="none" stroke={s.text} strokeOpacity=".25" strokeWidth="4"/>
          <circle cx="17" cy="17" r={r} fill="none" stroke={s.accent} strokeWidth="4" strokeLinecap="round"
            strokeDasharray={c} strokeDashoffset={c*(1-pct/100)}/>
        </svg>
      </div>
    );
  }
  if (t === 'checklist') {
    return (
      <div style={box}>
        <div className="flex flex-col gap-[4px] w-[70%]">
          {[0,1,2].map(i=>(
            <div key={i} className="flex items-center gap-[3px]">
              <span className="w-[6px] h-[6px] rounded-[2px] grid place-items-center" style={{ background:s.accent }}>
                <span style={{ width:3, height:3 }}/></span>
              <span className="h-[3px] rounded-full flex-1" style={{ background:s.text, opacity:.4 }}/>
            </div>
          ))}
        </div>
      </div>
    );
  }
  if (t === 'quote') {
    return (
      <div style={box}>
        <div className="flex flex-col items-center">
          <span className={fc} style={{ fontSize:18, color:s.accent, lineHeight:.6, fontWeight:s.weight }}>“</span>
          <div className="flex flex-col gap-[3px] w-[60%] mt-[2px]">
            {[0,1].map(i=><span key={i} className="h-[3px] rounded-full" style={{ background:s.text, opacity:.5 }}/>)}
          </div>
        </div>
      </div>
    );
  }
  if (t === 'timeline') {
    return (
      <div style={box}>
        <div className="flex items-center gap-[3px]">
          <span className="w-[7px] h-[7px] rounded-full" style={{ background:s.text, opacity:.35 }}/>
          <span className="h-[2px] w-[10px]" style={{ background:s.text, opacity:.3 }}/>
          <span className="w-[8px] h-[8px] rounded-full" style={{ background:s.accent }}/>
        </div>
      </div>
    );
  }
  if (t === 'iconrow') {
    return (
      <div style={box}>
        <div className="flex gap-[4px]">
          {[0,1,2].map(i=><span key={i} className="w-[8px] h-[8px] rounded-full" style={{ background:i===1?s.accent:s.text, opacity:i===1?1:.4 }}/>)}
        </div>
      </div>
    );
  }
  return <div style={box} />;
}

/* ============ BIG (inside the 9:16 reel preview) — uses cqw units ============ */
function BigTreatment({ scene, style, loopKey }) {
  const s = style, p = scene.payload || {};
  const fc = fontClassOf(s.font);
  const t = scene.treatment;
  const accentGlow = s.glow ? `0 0 18px ${s.accent}, 0 0 40px ${s.accent}66` : 'none';

  const wrap = "absolute inset-0 flex flex-col items-center justify-center px-[9%] text-center";

  if (t === 'text') {
    const ROLE = { small:{size:7.4,op:.78,mb:1.5}, hook:{size:14,op:1,mb:.6}, stat:{size:21,op:1,mb:.6}, punch:{size:15,op:1,mb:.6} };
    return (
      <div className={wrap}>
        {(p.lines||[]).map((ln,i)=>{
          const r = ROLE[ln.role]||ROLE.hook;
          const accent = ln.accent;
          return (
            <div key={`${loopKey}-${i}`} className={`reel-line ${fc}`} style={{
              fontSize:`${r.size}cqw`, fontWeight:s.weight, lineHeight: ln.role==='small'?1.05:.92,
              letterSpacing:s.tracking, color: accent? s.accent : s.text, opacity:r.op,
              textTransform: s.upper?'uppercase':'none', textShadow: accent?accentGlow:'none',
              fontStyle: s.font==='serif'&&accent?'italic':'normal', marginBottom:`${r.mb}cqw`,
              animation:`${animName(s)} .6s cubic-bezier(.2,.85,.25,1) both`, animationDelay:`${i*0.13}s`,
            }}>{ln.t}</div>
          );
        })}
      </div>
    );
  }

  if (t === 'bars') {
    return (
      <div className={wrap}>
        <div className={fc} style={{ fontSize:'6cqw', color:s.text, opacity:.7, marginBottom:'7cqw', textTransform:s.upper?'uppercase':'none' }}>{p.title}</div>
        <div className="flex items-end justify-center gap-[10%] w-full" style={{ height:'42cqw' }}>
          {[p.a,p.b].map((d,i)=>(
            <div key={`${loopKey}-${i}`} className="flex flex-col items-center justify-end h-full" style={{ width:'30%' }}>
              <div className={fc} style={{ fontSize:'8cqw', fontWeight:s.weight, color:i===1?s.accent:s.text, marginBottom:'2cqw' }}>{d.val}</div>
              <div style={{ width:'100%', height:`${d.pct}%`, minHeight:'6%', background:i===1?s.accent:s.text, opacity:i===1?1:.3, borderRadius:'2cqw 2cqw 0 0',
                transformOrigin:'bottom', animation:'growbar .7s cubic-bezier(.2,.9,.2,1) both', animationDelay:`${i*0.18+0.1}s`, boxShadow:i===1?accentGlow:'none' }}/>
              <div className={fc} style={{ fontSize:'5.4cqw', color:s.text, opacity:.6, marginTop:'2.5cqw', textTransform:s.upper?'uppercase':'none' }}>{d.label}</div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (t === 'counter') {
    return (
      <div className={wrap}>
        <div key={`${loopKey}`} className={fc} style={{ fontSize:'34cqw', fontWeight:s.weight, color:s.accent, lineHeight:.85,
          letterSpacing:s.tracking, textShadow:accentGlow, animation:'countup .6s cubic-bezier(.2,.85,.2,1) both' }}>{p.value}</div>
        <div className={fc} style={{ fontSize:'9cqw', fontWeight:s.weight, color:s.text, marginTop:'1cqw', textTransform:s.upper?'uppercase':'none' }}>{p.unit}</div>
        <div className={fc} style={{ fontSize:'5.4cqw', color:s.text, opacity:.6, marginTop:'4cqw' }}>{p.caption}</div>
      </div>
    );
  }

  if (t === 'ring') {
    const pct = p.pct ?? 72, r=42, c=2*Math.PI*r;
    return (
      <div className={wrap}>
        <div className="relative" style={{ width:'56cqw', height:'56cqw' }}>
          <svg viewBox="0 0 100 100" className="w-full h-full -rotate-90">
            <circle cx="50" cy="50" r={r} fill="none" stroke={s.text} strokeOpacity=".2" strokeWidth="8"/>
            <circle key={loopKey} cx="50" cy="50" r={r} fill="none" stroke={s.accent} strokeWidth="8" strokeLinecap="round"
              style={{ '--circ':c, '--off':c*(1-pct/100), strokeDasharray:c, animation:'ringdraw 1s cubic-bezier(.3,.9,.3,1) both' }}/>
          </svg>
          <div className="absolute inset-0 grid place-items-center">
            <span className={fc} style={{ fontSize:'15cqw', fontWeight:s.weight, color:s.text }}>{pct}%</span>
          </div>
        </div>
        {p.caption && <div className={fc} style={{ fontSize:'5.4cqw', color:s.text, opacity:.6, marginTop:'4cqw' }}>{p.caption}</div>}
      </div>
    );
  }

  if (t === 'checklist') {
    const items = p.items || ['Faster','Cheaper','Copyable'];
    return (
      <div className={wrap}>
        <div className="flex flex-col gap-[4cqw] w-full">
          {items.map((it,i)=>(
            <div key={`${loopKey}-${i}`} className="flex items-center gap-[4cqw]" style={{ animation:'checkpop .4s cubic-bezier(.2,.85,.2,1) both', animationDelay:`${i*0.2}s` }}>
              <span className="grid place-items-center shrink-0" style={{ width:'10cqw', height:'10cqw', borderRadius:'3cqw', background:s.accent }}>
                <svg viewBox="0 0 24 24" width="60%" height="60%" fill="none" stroke={s.bg} strokeWidth="4" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
              </span>
              <span className={fc} style={{ fontSize:'7cqw', fontWeight:s.weight, color:s.text, textTransform:s.upper?'uppercase':'none' }}>{it}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (t === 'quote') {
    return (
      <div className={wrap}>
        <div className={fc} style={{ fontSize:'30cqw', color:s.accent, lineHeight:.5, fontWeight:s.weight, textShadow:accentGlow }}>“</div>
        <div key={loopKey} className={fc} style={{ fontSize:'9cqw', fontWeight:s.weight, color:s.text, lineHeight:1.1, marginTop:'2cqw',
          fontStyle:s.font==='serif'?'italic':'normal', animation:'softfade .6s ease both' }}>{p.text || 'Anyone can copy it.'}</div>
      </div>
    );
  }

  if (t === 'timeline') {
    return (
      <div className={wrap}>
        <div className="flex items-center justify-center gap-[4cqw] w-full">
          {[p.a,p.b].map((d,i)=>(
            <React.Fragment key={i}>
              {i===1 && <span style={{ flex:'0 0 14%', height:'1.4cqw', background:s.text, opacity:.3 }}/>}
              <div className="flex flex-col items-center" style={{ animation:'countup .5s ease both', animationDelay:`${i*0.2}s` }}>
                <span style={{ width:'9cqw', height:'9cqw', borderRadius:'99px', background:i===1?s.accent:s.text, opacity:i===1?1:.35, boxShadow:i===1?accentGlow:'none' }}/>
                <span className={fc} style={{ fontSize:'7cqw', fontWeight:s.weight, color:i===1?s.accent:s.text, marginTop:'3cqw' }}>{(d&&d.val)||(i?'Now':'Then')}</span>
                <span className={fc} style={{ fontSize:'5cqw', color:s.text, opacity:.6, marginTop:'1cqw' }}>{(d&&d.label)||''}</span>
              </div>
            </React.Fragment>
          ))}
        </div>
      </div>
    );
  }

  if (t === 'iconrow') {
    const items = p.items || [['⚡','Fast'],['💸','Cheap'],['🧬','Copyable']];
    return (
      <div className={wrap}>
        <div className="flex justify-center gap-[7cqw]">
          {items.map((it,i)=>(
            <div key={`${loopKey}-${i}`} className="flex flex-col items-center" style={{ animation:'countup .45s ease both', animationDelay:`${i*0.15}s` }}>
              <span style={{ fontSize:'13cqw' }}>{it[0]}</span>
              <span className={fc} style={{ fontSize:'5cqw', color:s.text, opacity:.75, marginTop:'2cqw', textTransform:s.upper?'uppercase':'none' }}>{it[1]}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  return null;
}

function animName(s){ return ({ slam:'slam', softfade:'softfade', neonin:'neonin', type:'typereveal', rise:'riseword' })[s.anim] || 'softfade'; }

window.MiniTreatment = MiniTreatment;
window.BigTreatment = BigTreatment;
window.fontClassOf = fontClassOf;
