/* ─── Create Promotion — "Studio" layout ─────────────────────────────────────
   Phase 1: visual type gallery. Phase 2: studio editor — grouped controls
   left, phone-framed customer preview right, sticky create bar on top. */

const STUDIO_TYPES = [
  { t:'Warranty',            icon:'shield',     d:'Register the purchase for warranty cover' },
  { t:'Extended Warranty',   icon:'shield-ext', d:'Extra cover in exchange for a review' },
  { t:'Cashback',            icon:'cash',       d:'Money back after purchase' },
  { t:'Coupon code',         icon:'coupon',     d:'Discount code for the next order' },
  { t:'Gift Card',           icon:'gift',       d:'Gift card reward for reviewers' },
  { t:'Product Information', icon:'info',       d:'Manuals, tips & product guides' },
  { t:'Digital Download',    icon:'cloud',      d:'Deliver a digital file instantly' },
  { t:'Product Giveaway',    icon:'box',        d:'Free product for top reviewers' },
];

/* Per-type CTA suggestions — shared with the classic create form */
window.RB_CTA_OPTIONS = {
  'Warranty':            ['Claim My Warranty','Activate Warranty','Register My Purchase'],
  'Extended Warranty':   ['Extend My Warranty','Activate Extra Cover','Claim Extended Cover'],
  'Cashback':            ['Claim My Cashback','Get My Money Back','Redeem Cashback'],
  'Coupon code':         ['Get My Coupon','Reveal My Code','Claim My Discount'],
  'Gift Card':           ['Claim My Gift Card','Redeem Gift Card','Get My Reward'],
  'Product Information': ['View Product Guide','Get The Manual','Show Me How'],
  'Digital Download':    ['Download Now','Get My Download','Access My File'],
  'Product Giveaway':    ['Enter Giveaway','Claim Free Product','Join The Giveaway'],
};

/* Editable text input with a per-type suggestion dropdown */
function ComboText({ value, onChange, options = [], placeholder }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const h = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h); return () => document.removeEventListener('mousedown', h);
  }, [open]);
  return (
    <div ref={ref} className="relative">
      <input value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder}
        className="w-full bg-surface-input rounded-lg pl-3 pr-9 py-3 text-[13px] text-ink placeholder:text-slate-400 outline-none focus:ring-2 focus:ring-[var(--accent-ring)]"/>
      {options.length > 0 && (
        <button type="button" onClick={()=>setOpen(o=>!o)} aria-label="Show suggestions"
          className="absolute right-1.5 top-1/2 -translate-y-1/2 w-7 h-7 rounded-md text-ink-soft hover:text-ink hover:bg-white flex items-center justify-center transition-colors">
          <svg className={"transition-transform "+(open?"rotate-180":"")} width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M6 9l6 6 6-6" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </button>
      )}
      {open && (
        <div className="absolute z-30 top-full mt-1 left-0 right-0 bg-white border border-line rounded-xl shadow-pop max-h-52 overflow-y-auto py-1">
          {options.map((o,i)=>(
            <button key={i} type="button" onClick={()=>{onChange(o); setOpen(false);}}
              className={"w-full text-left px-3.5 py-2 text-[12.5px] hover:bg-surface-subtle transition-colors "+(o===value?"font-bold acc-text":"text-ink")}>
              {o.replace(/\*/g,'')}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
window.ComboText = ComboText;

function StudioSection({ title, open, onToggle, children }) {
  return (
    <div className="bg-white rounded-2xl border border-line shadow-soft overflow-visible">
      <button onClick={onToggle} className="w-full flex items-center justify-between px-5 py-4">
        <span className="text-[13px] font-bold text-ink">{title}</span>
        <svg className={"text-ink-soft transition-transform "+(open?"rotate-180":"")} width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M6 9l6 6 6-6" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </button>
      {open && <div className="px-5 pb-5">{children}</div>}
    </div>
  );
}

function CreatePromotionStudio({ ctx }) {
  const PD     = window.PROMOS_DATA || [];
  const themes = window.TH_DATA || [];
  const idxOf  = t => (TYPE_TO_PROMO_IDX[t] ?? 0);

  const [type,     setType]     = React.useState(ctx?.type || null);   // null = gallery
  const [name,     setName]     = React.useState('');
  const [title,    setTitle]    = React.useState('');
  const [desc,     setDesc]     = React.useState('');
  const [features, setFeatures] = React.useState([]);
  const [themeIdx, setThemeIdx] = React.useState(0);
  const [animIdx,  setAnimIdx]  = React.useState(0);
  const [ctaText,  setCtaText]  = React.useState('');
  const [presetI,  setPresetI]  = React.useState(0);
  const [brand,     setBrand]     = React.useState((window.RB_BRANDS||[{name:'Brontix'}])[0]?.name || 'Brontix');
  const [openSec,  setOpenSec]  = React.useState({ content:true, style:true, anim:false });

  const applyType = (t) => {
    const p = PD[idxOf(t)] || {};
    setType(t);
    setTitle(p.copies?.[0]?.t || '');
    setDesc(p.copies?.[0]?.s || '');
    setFeatures((p.pills || []).slice(0,3).map(x=>x.lb));
    setThemeIdx(p.th ?? 0);
    setAnimIdx(0); setPresetI(0);
  };
  React.useEffect(() => { if (ctx?.type) applyType(ctx.type); }, []);

  const promoIdx = idxOf(type || 'Warranty');
  const pd       = PD[promoIdx] || {};
  const valid    = name.trim().length > 0;
  const toggleSec = k => setOpenSec(o => ({...o, [k]: !o[k]}));
  const updateFeature = (i,v) => { const nf=[...features]; nf[i]=v; setFeatures(nf); };
  const applyPreset = (i) => {
    const cp = (pd.copies||[])[i]; if (!cp) return;
    setPresetI(i); setTitle(cp.t); setDesc(cp.s);
  };

  /* ── Phase 1: type gallery ── */
  if (!type) return (
    <>
      <PageHeader crumbs={['Promotions','Create Promotion']} title="Create Promotion"/>
      <div className="px-7 py-6">
        <p className="text-[13.5px] text-ink-muted mb-5">What do you want to offer customers? Pick a promotion type to start — everything is pre-filled and editable.</p>
        <div className="grid gap-4" style={{gridTemplateColumns:'repeat(auto-fill, minmax(240px, 1fr))'}}>
          {STUDIO_TYPES.map(s => (
            <button key={s.t} onClick={()=>applyType(s.t)}
              className="group text-left bg-white rounded-2xl border border-line shadow-soft hover:shadow-card hover:border-[var(--accent)] transition-all p-5 flex flex-col gap-3">
              <span className="w-11 h-11 rounded-xl bg-surface-input flex items-center justify-center"><PromoIcon kind={s.icon}/></span>
              <div>
                <p className="font-bold text-[14px] text-ink">{s.t}</p>
                <p className="text-[12px] text-ink-muted mt-1 leading-snug">{s.d}</p>
              </div>
              <span className="mt-auto text-[12px] font-bold acc-text opacity-0 group-hover:opacity-100 transition-opacity">Start with this →</span>
            </button>
          ))}
        </div>
      </div>
    </>
  );

  /* ── Phase 2: studio editor ── */
  return (
    <>
      <PageHeader crumbs={['Promotions','Create Promotion']} title="Create Promotion"/>
      <div className="px-7 py-6 flex flex-col gap-5">

        {/* sticky top bar: type · name · create */}
        <div className="flex items-center gap-3 flex-wrap bg-white border border-line rounded-2xl px-4 py-3 shadow-soft sticky top-[76px] z-20">
          <button onClick={()=>setType(null)}
            className="inline-flex items-center gap-2 pl-1.5 pr-3 py-1.5 rounded-full bg-surface-input hover:bg-surface-subtle border border-transparent hover:border-line transition-colors">
            <span className="w-7 h-7 rounded-lg bg-white border border-line flex items-center justify-center"><PromoIcon kind={STUDIO_TYPES.find(s=>s.t===type)?.icon || 'shield'}/></span>
            <span className="text-[12.5px] font-bold text-ink">{type}</span>
            <span className="text-[11px] font-bold acc-text">Change</span>
          </button>
          <div className="h-5 w-px bg-line"></div>
          <Input placeholder="Promotion name (internal)" value={name} onChange={e=>setName(e.target.value)} className="!w-60 !py-2.5"/>
          <Select value={brand} onChange={e=>setBrand(e.target.value)} className="!w-36 !py-2.5" title="Brand — manage in Settings → Brand Details">
            {(window.RB_BRANDS || [{name:'Brontix'}]).map(b=><option key={b.name}>{b.name}</option>)}
            <option value="__none__">Don't show a brand</option>
          </Select>
          <div className="flex-1"></div>
          {!valid && <span className="text-[12px] text-ink-soft hidden md:inline">Name your promotion to create it</span>}
          <BtnPrimary disabled={!valid}>Create Promotion</BtnPrimary>
        </div>

        <div className="flex gap-6 items-start">
          {/* left: grouped controls */}
          <div className="flex-1 min-w-0 flex flex-col gap-4">

            <StudioSection title="Content" open={openSec.content} onToggle={()=>toggleSec('content')}>
              <div className="space-y-4">
                {(pd.copies||[]).length > 1 && (
                  <div>
                    <p className="text-[11px] font-bold uppercase tracking-wider text-ink-muted mb-2">Starting points</p>
                    <div className="flex flex-wrap gap-2">
                      {(pd.copies||[]).map((cp,i)=>(
                        <button key={i} onClick={()=>applyPreset(i)}
                          className={"px-3 py-1.5 rounded-full text-[12px] font-bold border transition-colors "+(presetI===i && title===cp.t ? "acc-bg text-white border-transparent" : "bg-white text-ink-muted border-line hover:border-ink-soft hover:text-ink")}>
                          {cp.t.replace(/\*/g,'')}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
                <div>
                  <p className="text-[11px] font-bold uppercase tracking-wider text-ink-muted mb-1.5">Title <span className="normal-case font-normal text-ink-soft">· pick a suggestion or write your own · wrap a *word* to accent it</span></p>
                  <ComboText placeholder="e.g. Secure Your *Purchase!*" value={title} onChange={setTitle} options={(pd.copies||[]).map(cp=>cp.t)}/>
                </div>
                <div className="grid sm:grid-cols-2 gap-4">
                  <div>
                    <p className="text-[11px] font-bold uppercase tracking-wider text-ink-muted mb-1.5">Subtitle</p>
                    <ComboText placeholder="Supporting line" value={desc} onChange={setDesc} options={(pd.copies||[]).map(cp=>cp.s)}/>
                  </div>
                  <div>
                    <p className="text-[11px] font-bold uppercase tracking-wider text-ink-muted mb-1.5">CTA button text</p>
                    <ComboText placeholder={pd.cta || 'Claim My Warranty'} value={ctaText} onChange={setCtaText} options={window.RB_CTA_OPTIONS[type] || []}/>
                  </div>
                </div>
                <div>
                  <p className="text-[11px] font-bold uppercase tracking-wider text-ink-muted mb-1.5">Feature pills</p>
                  <div className="grid grid-cols-3 gap-2">
                    {[0,1,2].map(i=>(
                      <Input key={i} placeholder={(pd.pills?.[i]?.lb)||('Feature '+(i+1))} value={features[i]||''} onChange={e=>updateFeature(i,e.target.value)}/>
                    ))}
                  </div>
                </div>
              </div>
            </StudioSection>

            <StudioSection title="Style" open={openSec.style} onToggle={()=>toggleSec('style')}>
              <div className="flex items-center gap-2.5 flex-wrap">
                {themes.map((th,i)=>(
                  <button key={i} onClick={()=>setThemeIdx(i)} title={th.n}
                    style={{width:26,height:26,borderRadius:'50%',background:th.c,border:'none',cursor:'pointer',flexShrink:0,
                      boxShadow: i===themeIdx ? `0 0 0 2px white, 0 0 0 4px ${th.c}` : 'none',transition:'box-shadow .15s'}}/>
                ))}
              </div>
            </StudioSection>

            <StudioSection title="Animation" open={openSec.anim} onToggle={()=>toggleSec('anim')}>
              {typeof AnimPicker !== 'undefined' && (
                <AnimPicker promoIdx={promoIdx} themeIdx={themeIdx} value={animIdx} onChange={setAnimIdx}/>
              )}
            </StudioSection>
          </div>

          {/* right: customer-context phone preview */}
          <div className="shrink-0 lg:sticky lg:top-[150px] hidden md:block">
            <PhonePreview label="Customer preview">
              <div className="flex-1 overflow-y-auto no-scrollbar bg-surface-subtle">
                <div className="text-center pt-4 pb-2" style={{minHeight:30}}>
                  {brand !== '__none__' && <span className="text-[10px] tracking-[0.18em] font-bold text-gray-500 uppercase">{brand}</span>}
                </div>
                <div style={{transform:'scale(0.585)',transformOrigin:'top center',width:360,marginLeft:-70}}>
                  <div style={{width:360,margin:'0 auto'}}>
                    {typeof PromoCard !== 'undefined' && (
                      <PromoCard promoIdx={promoIdx} themeIdx={themeIdx} animIdx={animIdx} brand={brand}
                        title={title} subtitle={desc} features={features} cta={ctaText}/>
                    )}
                  </div>
                </div>
              </div>
            </PhonePreview>
          </div>
        </div>
      </div>
    </>
  );
}

window.CreatePromotionStudio = CreatePromotionStudio;
