/* ─── Products page — v2 redesign ────────────────────────────────────────────
   Fresh layout: stat strip → toolbar (search / campaign filter / view toggle)
   → card grid (default) or refined table. Overrides window.Products. */

const PRODUCTS_V2 = [
  { name:'FRANCE',                    mkt:['amazon','shopify','ebay','etsy','gmb'], camp:0 },
  { name:'ITALY PRODUCT',             mkt:['amazon','shopify','temu','ebay','etsy','gmb'], camp:0 },
  { name:'Spain Testing',             mkt:['amazon','shopify','temu','ebay','etsy','gmb'], camp:1 },
  { name:'Australia Product Testing', mkt:['shopify','temu','ebay','etsy','amazon','gmb'], camp:1 },
  { name:'USA testing',               mkt:['amazon','shopify','walmart','target','airbnb','trustpilot','yelp'], camp:1 },
  { name:'UK testing',                mkt:['amazon','temu','ebay','shopify','google'], camp:1 },
  { name:'Brontix Wifi Router',       mkt:['amazon','shopify','google','etsy','myntra','flipkart','tatacliq','ajio'], camp:9 },
  { name:'Breast Pump First Cry',     mkt:['nykaa','firstcry','ebay','etsy'], camp:1 },
  { name:'Apartment',                 mkt:['airbnb'], camp:1 },
  { name:'Bedsure Queen Comforter',   mkt:['amazon'], camp:2 },
];

const MKT_META = {
  amazon:{bg:'bg-amber-50',text:'text-amber-700',label:'amazon'}, shopify:{bg:'bg-green-50',text:'text-green-700',label:'shopify'},
  ebay:{bg:'bg-rose-50',text:'text-rose-600',label:'eBay'}, etsy:{bg:'bg-orange-50',text:'text-orange-700',label:'Etsy'},
  gmb:{bg:'bg-orange-100',text:'text-orange-700',label:'GMB'}, temu:{bg:'bg-orange-50',text:'text-orange-700',label:'TEMU'},
  walmart:{bg:'bg-sky-50',text:'text-sky-700',label:'Walmart'}, target:{bg:'bg-rose-50',text:'text-rose-700',label:'TARGET'},
  airbnb:{bg:'bg-rose-50',text:'text-rose-600',label:'airbnb'}, trustpilot:{bg:'bg-green-50',text:'text-green-700',label:'Trustpilot'},
  yelp:{bg:'bg-rose-50',text:'text-rose-700',label:'yelp'}, google:{bg:'bg-blue-50',text:'text-blue-700',label:'Google'},
  myntra:{bg:'bg-rose-50',text:'text-rose-600',label:'Myntra'}, flipkart:{bg:'bg-amber-50',text:'text-amber-700',label:'Flipkart'},
  tatacliq:{bg:'bg-rose-50',text:'text-rose-700',label:'TATA CLiQ'}, ajio:{bg:'bg-slate-100',text:'text-slate-700',label:'AJIO'},
  nykaa:{bg:'bg-rose-50',text:'text-rose-700',label:'NYKAA'}, firstcry:{bg:'bg-orange-50',text:'text-orange-700',label:'firstcry'},
};

const MktChips = ({ list, max = 3 }) => {
  const shown = list.slice(0, max), rest = list.length - shown.length;
  return (
    <div className="flex flex-wrap items-center gap-1.5">
      {shown.map((k,i) => {
        const m = MKT_META[k] || {bg:'bg-slate-100',text:'text-slate-600',label:k};
        return <span key={i} className={"text-[10px] font-bold px-1.5 py-1 rounded "+m.bg+" "+m.text}>{m.label}</span>;
      })}
      {rest > 0 && (
        <span title={list.slice(max).map(k => (MKT_META[k]||{label:k}).label).join(', ')}
              className="text-[10px] font-bold px-1.5 py-1 rounded bg-surface-input text-ink-muted cursor-default">+{rest}</span>
      )}
    </div>
  );
};

const CampBadge = ({ n }) => n > 0
  ? <span className="inline-flex items-center gap-1.5 text-[11px] font-bold px-2.5 py-1 rounded-full acc-bg-soft acc-text">
      <span className="w-1.5 h-1.5 rounded-full acc-bg"></span><span className="whitespace-nowrap">{`${n} campaign${n>1?'s':''}`}</span>
    </span>
  : <span className="inline-flex items-center gap-1.5 text-[11px] font-bold px-2.5 py-1 rounded-full bg-surface-input text-ink-soft">
      <span className="w-1.5 h-1.5 rounded-full bg-ink-soft/50"></span><span className="whitespace-nowrap">No campaign</span>
    </span>;

const QrIcon = () => (
  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2">
    <rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/>
    <path d="M14 14h3v3h-3zM20 14h1M14 20h1M18 18h3v3h-3z"/>
  </svg>
);

const StatTileV2 = ({ label, value, sub, active, onClick }) => (
  <button onClick={onClick}
    className={"text-left rounded-2xl border px-5 py-4 transition-all "+(active
      ? "bg-white border-brand-200 shadow-card ring-1 ring-brand-200"
      : "bg-white border-line shadow-soft hover:border-brand-200")}>
    <p className="text-[11.5px] font-bold uppercase tracking-[0.1em] text-ink-muted">{label}</p>
    <p className="mt-1.5 text-[26px] font-extrabold tracking-tight text-ink leading-none">{value}</p>
    <p className="mt-1.5 text-[12px] text-ink-soft">{sub}</p>
  </button>
);

const CardActions = ({ onNav, className='' }) => (
  <div className={"flex gap-1.5 "+className}>
    <button title="Edit" onClick={()=>onNav('product-add')} className="w-8 h-8 rounded-lg bg-white/90 backdrop-blur text-ink-muted hover:text-brand flex items-center justify-center shadow-sm">
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M18.5 2.5a2.1 2.1 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
    </button>
    <button title="Delete" className="w-8 h-8 rounded-lg bg-white/90 backdrop-blur text-ink-muted hover:text-rose-600 flex items-center justify-center shadow-sm">
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>
    </button>
  </div>
);

/* stand-in for the real product photo — contained, never cropped */
const PhotoStandin = ({ hue, className='' }) => (
  <span className={"block rounded-xl "+className}
        style={{background:`linear-gradient(135deg, hsl(${hue},75%,72%), hsl(${(hue+40)%360},65%,50%))`}}></span>
);

const CardFooterLink = ({ p, onNav }) => p.camp === 0
  ? <button onClick={()=>onNav('campaign-add')} className="font-bold text-brand hover:text-brand-dark">Add to campaign →</button>
  : <button onClick={()=>onNav('campaigns')} className="font-bold text-ink-muted hover:text-ink">View campaigns →</button>;

/* 1 — Image well: 4:3 contained photo area, info below */
function CardImageWell({ p, hue, onNav }) {
  return (
    <div className="group bg-white rounded-2xl border border-line shadow-soft hover:shadow-card hover:border-brand-200 transition-all flex flex-col overflow-hidden">
      <div className="relative aspect-[4/3] bg-surface-subtle border-b border-line/70 flex items-center justify-center p-6">
        <PhotoStandin hue={hue} className="w-full h-full max-w-[62%] max-h-[80%] mx-auto"/>
        <span className="absolute top-3 left-3"><CampBadge n={p.camp}/></span>
        <CardActions onNav={onNav} className="absolute top-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity"/>
      </div>
      <div className="px-4 pt-3.5 pb-4 flex-1 flex flex-col gap-3">
        <p className="font-bold text-[14px] text-ink leading-snug">{p.name}</p>
        <MktChips list={p.mkt}/>
        <div className="mt-auto pt-3 border-t border-line/70 flex items-center justify-between text-[12px]">
          <span className="text-ink-muted">{p.mkt.length} marketplace{p.mkt.length>1?'s':''}</span>
          <CardFooterLink p={p} onNav={onNav}/>
        </div>
      </div>
    </div>
  );
}

/* 2 — Side thumb: horizontal, dense */
function CardSideThumb({ p, hue, onNav }) {
  return (
    <div className="group bg-white rounded-2xl border border-line shadow-soft hover:shadow-card hover:border-brand-200 transition-all p-4 flex gap-4">
      <PhotoStandin hue={hue} className="w-[72px] h-[72px] shrink-0"/>
      <div className="min-w-0 flex-1 flex flex-col gap-2">
        <div className="flex items-start justify-between gap-2">
          <p className="font-bold text-[14px] text-ink leading-snug">{p.name}</p>
          <CardActions onNav={onNav} className="opacity-0 group-hover:opacity-100 transition-opacity shrink-0 -mt-1"/>
        </div>
        <MktChips list={p.mkt}/>
        <div className="mt-auto pt-2 flex items-center justify-between text-[12px]">
          <CampBadge n={p.camp}/>
          <CardFooterLink p={p} onNav={onNav}/>
        </div>
      </div>
    </div>
  );
}

/* 3 — Square tile: image-led storefront grid */
function CardSquareTile({ p, hue, onNav }) {
  return (
    <div className="group bg-white rounded-2xl border border-line shadow-soft hover:shadow-card hover:border-brand-200 transition-all flex flex-col overflow-hidden">
      <div className="relative aspect-square bg-surface-subtle flex items-center justify-center p-7">
        <PhotoStandin hue={hue} className="w-full h-full rounded-2xl"/>
        <span className="absolute top-3 left-3"><CampBadge n={p.camp}/></span>
        <CardActions onNav={onNav} className="absolute bottom-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity"/>
      </div>
      <div className="px-4 py-3.5 flex flex-col gap-2">
        <p className="font-bold text-[13.5px] text-ink leading-snug truncate" title={p.name}>{p.name}</p>
        <MktChips list={p.mkt} max={2}/>
      </div>
    </div>
  );
}

const CARD_STYLES = { 'Image well':CardImageWell, 'Side thumb':CardSideThumb, 'Square tile':CardSquareTile };
const CARD_MIN_W  = { 'Image well':250, 'Side thumb':330, 'Square tile':210 };

function ProductsV2({ onNav, cardStyle='Image well' }) {
  const CardComp = CARD_STYLES[cardStyle] || CardImageWell;
  const [query, setQuery] = React.useState('');
  const [filter, setFilter] = React.useState('all');   // all | in | none
  const [view, setView] = React.useState('list');      // grid | list
  const [fMkt, setFMkt] = React.useState('All marketplaces');
  const mktOpts = ['All marketplaces', ...new Set(PRODUCTS_V2.flatMap(p=>p.mkt))].sort((a,b)=>a==='All marketplaces'?-1:b==='All marketplaces'?1:a.localeCompare(b));
  const rows = PRODUCTS_V2
    .filter(p => p.name.toLowerCase().includes(query.toLowerCase()))
    .filter(p => fMkt==='All marketplaces' || p.mkt.includes(fMkt))
    .filter(p => filter === 'all' ? true : filter === 'in' ? p.camp > 0 : p.camp === 0);
  const inCamp = PRODUCTS_V2.filter(p=>p.camp>0).length;
  const noCamp = PRODUCTS_V2.length - inCamp;
  const markets = new Set(PRODUCTS_V2.flatMap(p=>p.mkt)).size;
  const seg = (id,label) => (
    <button onClick={()=>setFilter(id)}
      className={"px-3.5 py-2 rounded-lg text-[12.5px] font-bold transition-colors "+(filter===id?"bg-white text-ink shadow-sm":"text-ink-muted hover:text-ink")}>
      {label}
    </button>
  );
  const viewBtn = (id, path) => (
    <button onClick={()=>setView(id)} title={id}
      className={"w-9 h-9 rounded-lg flex items-center justify-center transition-colors "+(view===id?"bg-white text-brand shadow-sm":"text-ink-soft hover:text-ink")}>
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">{path}</svg>
    </button>
  );
  return (
    <>
      <PageHeader title="Products" action={
        <BtnPrimary icon={<PlusIcon/>} onClick={() => onNav('product-add')}>Add New Product</BtnPrimary>
      }/>
      <div className="px-7 py-6 space-y-5">
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <StatTileV2 label="All products" value={PRODUCTS_V2.length} sub={`across ${markets} marketplaces`} active={filter==='all'} onClick={()=>setFilter('all')}/>
          <StatTileV2 label="In campaigns" value={inCamp} sub="collecting reviews" active={filter==='in'} onClick={()=>setFilter('in')}/>
          <StatTileV2 label="No campaign" value={noCamp} sub="not collecting yet" active={filter==='none'} onClick={()=>setFilter('none')}/>
          <StatTileV2 label="Marketplaces" value={markets} sub="connected in total" onClick={()=>{}}/>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          <SearchInput placeholder="Search by product name" value={query} onChange={e=>setQuery(e.target.value)}/>
          <div className="flex items-center gap-1 bg-surface-input rounded-xl p-1">
            {seg('all','All')}{seg('in','In campaign')}{seg('none','No campaign')}
          </div>
          <select value={fMkt} onChange={e=>setFMkt(e.target.value)}
            className="h-11 bg-white border border-line rounded-xl px-3 text-[12.5px] font-semibold text-ink-muted outline-none focus:ring-2 focus:ring-brand-200 cursor-pointer">
            {mktOpts.map(m=><option key={m} value={m}>{m==='All marketplaces'?m:(MKT_META[m]||{label:m}).label}</option>)}
          </select>
          {fMkt!=='All marketplaces' && (
            <button onClick={()=>setFMkt('All marketplaces')} className="text-[12.5px] font-bold text-rose-500 hover:opacity-80">Clear filter</button>
          )}
          <div className="ml-auto flex items-center gap-1 bg-surface-input rounded-xl p-1">
            {viewBtn('grid', <g><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></g>)}
            {viewBtn('list', <g><path d="M8 6h13M8 12h13M8 18h13"/><circle cx="4" cy="6" r="1" fill="currentColor"/><circle cx="4" cy="12" r="1" fill="currentColor"/><circle cx="4" cy="18" r="1" fill="currentColor"/></g>)}
          </div>
        </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 products match</p>
            <p className="text-[13px] text-ink-muted mt-1">Try a different search or clear the filter.</p>
            <button onClick={()=>{setQuery('');setFilter('all');setFMkt('All marketplaces');}} className="mt-4 text-[13px] font-bold text-brand hover:text-brand-dark">Clear filters</button>
          </div>
        )}
        {view === 'grid' && rows.length > 0 && (
          <div className="grid gap-4" style={{gridTemplateColumns:`repeat(auto-fill, minmax(${CARD_MIN_W[cardStyle]||250}px, 1fr))`}}>
            {rows.map((p) => <CardComp key={p.name} p={p} hue={(PRODUCTS_V2.indexOf(p)*37)%360} onNav={onNav}/>)}
          </div>
        )}
        {view === 'list' && rows.length > 0 && (
          <Card className="overflow-hidden">
            <div className="overflow-x-auto">
            <table className="w-full min-w-[680px] text-[13px]" style={{tableLayout:'auto'}}>
              <thead>
                <tr className="bg-surface-subtle text-[11px] uppercase tracking-wider text-ink-muted border-b border-line">
                  <th className="text-left font-bold px-5 py-3 w-[30%]">Product</th>
                  <th className="text-left font-bold px-3 py-3">Marketplaces</th>
                  <th className="text-left font-bold px-3 py-3 whitespace-nowrap">Campaign</th>
                  <th className="text-right font-bold px-5 py-3">Action</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((p) => {
                  const hue = (PRODUCTS_V2.indexOf(p)*37)%360;
                  return (
                    <tr key={p.name} className="border-t border-gray-100 hover:bg-surface-subtle">
                      <td className="px-5 py-2.5">
                        <span className="flex items-center gap-2.5">
                          <span className="w-8 h-8 rounded-lg shrink-0" style={{background:`linear-gradient(135deg, hsl(${hue},75%,72%), hsl(${(hue+40)%360},65%,50%))`}}></span>
                          <span className="min-w-0">
                            <span className="block font-bold text-ink text-[13px] truncate">{p.name}</span>
                            <span className="block text-[11px] text-ink-soft">{p.mkt.length} marketplace{p.mkt.length>1?'s':''}</span>
                          </span>
                        </span>
                      </td>
                      <td className="px-3 py-2.5"><MktChips list={p.mkt} max={6}/></td>
                      <td className="px-3 py-2.5 whitespace-nowrap">{p.camp > 0
                        ? <CampBadge n={p.camp}/>
                        : <button onClick={()=>onNav('campaign-add')} className="text-[11.5px] font-bold acc-text hover:underline whitespace-nowrap">+ Add to campaign</button>}
                      </td>
                      <td className="px-5 py-2.5">
                        <span className="flex items-center gap-1 justify-end">
                          <RowActions onEdit={()=>onNav('product-add')}/>
                        </span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            </div>
          </Card>
        )}
        {rows.length > 0 && (
          <p className="text-[12px] text-ink-soft">Showing {rows.length} of {PRODUCTS_V2.length} products</p>
        )}
      </div>
    </>
  );
}

window.Products = ProductsV2;
ProductsV2.v2 = true;
