/* ─── Promotions page — v2 redesign ──────────────────────────────────────────
   Stat-tile filters → search + type chips → list rows (default) or cards.
   Overrides window.Promotions. Demo usage numbers invented. */

const PROMOS_V2 = [
  { name:'SPAIN',                          type:'Warranty',            icon:'shield',     camps:1, status:true,  created:'12 Jan 2026', delivered:14 },
  { name:'Australia Promotion',            type:'Warranty',            icon:'shield',     camps:1, status:true,  created:'03 Feb 2026', delivered:9 },
  { name:'cashback image test 2',          type:'Cashback',            icon:'cash',       camps:1, status:true,  created:'21 Feb 2026', delivered:22 },
  { name:'Product Information Test - Husain', type:'Product Information', icon:'info',    camps:0, status:true,  created:'08 Mar 2026', delivered:0 },
  { name:'Digital Download Test - Husain', type:'Digital Download',    icon:'cloud',      camps:1, status:true,  created:'15 Mar 2026', delivered:3 },
  { name:'Gift card Test - Husain',        type:'Gift Card',           icon:'gift',       camps:1, status:true,  created:'02 Apr 2026', delivered:8 },
  { name:'Cashback Test - Husain',         type:'Cashback',            icon:'cash',       camps:1, status:false, created:'11 Apr 2026', delivered:5 },
  { name:'Coupon code Test - Husain',      type:'Coupon code',         icon:'coupon',     camps:1, status:true,  created:'28 Apr 2026', delivered:11 },
  { name:'Product Giveaway Test - Husain', type:'Product Giveaway',    icon:'box',        camps:0, status:true,  created:'09 May 2026', delivered:0 },
  { name:'Extended Warranty Test - Husain',type:'Extended Warranty',   icon:'shield-ext', camps:1, status:true,  created:'25 May 2026', delivered:6 },
];

const PROMO_TYPE_CLS = {
  'Warranty':'bg-brand-50 text-brand', 'Extended Warranty':'bg-green-50 text-green-700',
  'Cashback':'bg-amber-50 text-amber-700', 'Coupon code':'bg-orange-50 text-orange-700',
  'Gift Card':'bg-blue-50 text-blue-700', 'Digital Download':'bg-sky-50 text-sky-700',
  'Product Information':'bg-sky-50 text-sky-700', 'Product Giveaway':'bg-cyan-50 text-cyan-700',
};
const TypeBadge = ({ type }) => (
  <span className={"inline-flex text-[10.5px] font-bold px-2 py-0.5 rounded-full whitespace-nowrap "+(PROMO_TYPE_CLS[type]||'bg-slate-100 text-slate-600')}>{type}</span>
);

const UsedIn = ({ n, onNav }) => n > 0
  ? <button onClick={()=>onNav('campaigns')} className="inline-flex items-center gap-1.5 text-[11.5px] font-bold px-2.5 py-1 rounded-full acc-bg-soft acc-text hover:opacity-80 whitespace-nowrap">
      <span className="w-1.5 h-1.5 rounded-full acc-bg"></span><span>{`${n} campaign${n>1?'s':''}`}</span>
    </button>
  : <span className="inline-flex items-center gap-1.5 text-[11.5px] font-bold px-2.5 py-1 rounded-full bg-amber-50 text-amber-700 whitespace-nowrap">
      <span className="w-1.5 h-1.5 rounded-full bg-amber-500"></span><span>Not used yet</span>
    </span>;

function PromoKebab({ onEdit }) {
  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]);
  const Item = ({ children, onClick, danger }) => (
    <button onClick={()=>{onClick&&onClick(); setOpen(false);}}
      className={"w-full text-left px-3.5 py-2 text-[12.5px] font-semibold rounded-lg transition-colors "+(danger?"text-rose-600 hover:bg-rose-50":"text-ink hover:bg-surface-subtle")}>
      {children}
    </button>
  );
  return (
    <div className="relative" ref={ref}>
      <button onClick={()=>setOpen(o=>!o)} className={"w-8 h-8 rounded-lg flex items-center justify-center transition-colors "+(open?"bg-surface-input text-ink":"text-ink-soft hover:bg-surface-input hover:text-ink")}>
        <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="1.8"/><circle cx="12" cy="12" r="1.8"/><circle cx="12" cy="19" r="1.8"/></svg>
      </button>
      {open && (
        <div className="absolute right-0 top-9 z-40 w-40 bg-white rounded-xl border border-line shadow-pop p-1.5">
          <Item onClick={onEdit}>Edit promotion</Item>
          <Item>Duplicate</Item>
          <Item danger>Delete</Item>
        </div>
      )}
    </div>
  );
}

/* mini stand-in for the customer-facing promo card preview (cards layout) */
const PromoMiniPreview = ({ icon, type }) => (
  <div className="rounded-xl bg-surface-subtle border border-line/70 p-3.5 flex items-center gap-3">
    <span className="w-9 h-9 rounded-lg bg-white border border-line flex items-center justify-center shrink-0"><PromoIcon kind={icon}/></span>
    <div className="min-w-0 flex-1">
      <div className="h-2 rounded-full bg-ink/10 w-3/4"></div>
      <div className="h-2 rounded-full bg-ink/5 w-1/2 mt-1.5"></div>
    </div>
    <span className="text-[9.5px] font-bold uppercase tracking-wider text-ink-soft">Claim card</span>
  </div>
);

const PROMO_COLS = 'minmax(190px,1.6fr) minmax(110px,1fr) minmax(90px,1fr) minmax(96px,1fr) minmax(84px,1fr) minmax(56px,.6fr) 76px';
function PromoListRows({ rows, onNav }) {
  return (
    <Card className="overflow-hidden">
      <div className="overflow-x-auto">
      <div className="min-w-[840px]">
      <div className="grid items-center gap-3 px-5 py-3 bg-surface-subtle text-[11px] font-bold uppercase tracking-wider text-ink-muted border-b border-line" style={{gridTemplateColumns:PROMO_COLS}}>
        <span>Promotion</span><span>Type</span><span>Created</span><span>Used in</span><span>Delivered</span><span>Status</span><span className="text-right">Action</span>
      </div>
      <div className="divide-y divide-gray-100">
      {rows.map((p) => (
        <div key={p.name} className="grid items-center gap-3 px-5 py-3 hover:bg-surface-subtle transition-colors" style={{gridTemplateColumns:PROMO_COLS}}>
          <span className="flex items-center gap-2.5 min-w-0">
            <span className="w-8 h-8 rounded-lg bg-surface-input flex items-center justify-center shrink-0"><PromoIcon kind={p.icon}/></span>
            <span className="font-bold text-[13px] text-ink truncate">{p.name}</span>
          </span>
          <span><TypeBadge type={p.type}/></span>
          <span className="text-[12px] text-ink-muted whitespace-nowrap">{p.created}</span>
          <span><UsedIn n={p.camps} onNav={onNav}/></span>
          <span className="text-[12.5px] whitespace-nowrap">{p.delivered > 0
            ? <><span className="font-extrabold text-ink">{p.delivered}</span> <span className="text-ink-muted">claims</span></>
            : <span className="text-ink-soft">—</span>}</span>
          <StatusToggle checked={p.status}/>
          <span className="flex justify-end"><PromoKebab onEdit={()=>onNav('promotion-create')}/></span>
        </div>
      ))}
      </div>
      </div>
      </div>
    </Card>
  );
}

function PromoCards({ rows, onNav }) {
  return (
    <div className="grid gap-4" style={{gridTemplateColumns:'repeat(auto-fill, minmax(280px, 1fr))'}}>
      {rows.map((p) => (
        <div key={p.name} className="bg-white rounded-2xl border border-line shadow-soft hover:shadow-card hover:border-brand-200 transition-all p-5 flex flex-col gap-4">
          <div className="flex items-start gap-3">
            <span className="w-10 h-10 rounded-xl bg-surface-input flex items-center justify-center shrink-0"><PromoIcon kind={p.icon}/></span>
            <div className="min-w-0 flex-1">
              <p className="font-bold text-[13.5px] text-ink leading-snug">{p.name}</p>
              <p className="mt-1"><TypeBadge type={p.type}/></p>
            </div>
            <StatusToggle checked={p.status}/>
          </div>
          <PromoMiniPreview icon={p.icon} type={p.type}/>
          <div className="pt-3 border-t border-line/70 flex items-center justify-between">
            <UsedIn n={p.camps} onNav={onNav}/>
            <PromoKebab onEdit={()=>onNav('promotion-create')}/>
          </div>
        </div>
      ))}
    </div>
  );
}

function PromotionsV2({ onNav, layout='List rows' }) {
  const [query, setQuery]   = React.useState('');
  const [filter, setFilter] = React.useState('all');   // all | active | unused
  const [type, setType]     = React.useState('All');
  const types = ['All', ...Array.from(new Set(PROMOS_V2.map(p=>p.type)))];
  const rows = PROMOS_V2
    .filter(p => p.name.toLowerCase().includes(query.toLowerCase()))
    .filter(p => type === 'All' ? true : p.type === type)
    .filter(p => filter === 'all' ? true : filter === 'active' ? p.status : p.camps === 0);
  const active = PROMOS_V2.filter(p=>p.status).length;
  const unused = PROMOS_V2.filter(p=>p.camps===0).length;
  return (
    <>
      <PageHeader title="Promotions" action={
        <span data-rb-live="true"><BtnPrimary icon={<PlusIcon/>} onClick={() => onNav('promotion-create')}>Create Promotion</BtnPrimary></span>
      }/>
      <div className="px-7 py-6 space-y-5">
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <StatTileV2 label="All promotions" value={PROMOS_V2.length} sub={`${types.length-1} promotion types`} active={filter==='all'} onClick={()=>setFilter('all')}/>
          <StatTileV2 label="Active" value={active} sub="switched on" active={filter==='active'} onClick={()=>setFilter('active')}/>
          <StatTileV2 label="Not used yet" value={unused} sub="not linked to a campaign" active={filter==='unused'} onClick={()=>setFilter('unused')}/>
          <StatTileV2 label="In campaigns" value={PROMOS_V2.reduce((a,p)=>a+p.camps,0)} sub="total placements" onClick={()=>{}}/>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          <SearchInput placeholder="Search by promotion name" value={query} onChange={e=>setQuery(e.target.value)}/>
        </div>
        <div className="flex flex-wrap gap-2">
          {types.map(tp => {
            const n = tp === 'All' ? PROMOS_V2.length : PROMOS_V2.filter(p=>p.type===tp).length;
            const on = type === tp;
            return (
              <button key={tp} onClick={()=>setType(tp)}
                className={"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-[12px] font-bold border transition-colors whitespace-nowrap "+(on?"bg-ink text-white border-ink":"bg-white text-ink-muted border-line hover:border-ink-soft hover:text-ink")}>
                {tp}<span className={on?"text-white/60":"text-ink-soft"}>{n}</span>
              </button>
            );
          })}
        </div>
        {rows.length === 0 ? (
          <div className="bg-white rounded-2xl border border-line shadow-soft py-16 text-center">
            <p className="text-[15px] font-bold text-ink">No promotions match</p>
            <p className="text-[13px] text-ink-muted mt-1">Try a different search or clear the filters.</p>
            <button onClick={()=>{setQuery('');setFilter('all');setType('All');}} className="mt-4 text-[13px] font-bold text-brand hover:text-brand-dark">Clear filters</button>
          </div>
        ) : layout === 'Cards' ? <PromoCards rows={rows} onNav={onNav}/> : <PromoListRows rows={rows} onNav={onNav}/>}
        {rows.length > 0 && <p className="text-[12px] text-ink-soft">Showing {rows.length} of {PROMOS_V2.length} promotions</p>}
      </div>
    </>
  );
}

window.Promotions = PromotionsV2;
PromotionsV2.v2 = true;
