/* ─── Seller Panel — Analytics: overview, funnel, products, marketplaces ── */

const AN_TABS = [
  { id:'overview', label:'Overview' },
  { id:'funnel',   label:'Funnel' },
  { id:'items',    label:'Products & Campaigns' },
  { id:'markets',  label:'Marketplaces' },
];

const AN_SERIES = [0,1,0,0,1,0,0,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1];
const AN_STARS = [ [5,5],[4,2],[3,1],[2,1],[1,0] ];
const AN_FUNNEL = [
  { lb:'QR scans / link opens', v:41, tip:'Every time a customer scanned your package-insert QR or opened a campaign link.' },
  { lb:'Claim started', v:20, tip:'Customers who began filling the claim form.' },
  { lb:'Claim completed', v:16, tip:'Customers who submitted a valid claim with order details.' },
  { lb:'Internal review left', v:9, tip:'Reviews written on your ReviewBuddie claim page — what your plan counts.' },
  { lb:'Copied review text', v:7, tip:'Customers who tapped “Copy review” — a strong signal they intend to post it externally.' },
  { lb:'Clicked to marketplace', v:6, tip:'Customers who clicked through to Amazon, Flipkart etc. We can’t verify posting — this is the best honest proxy.' },
];
const AN_ITEMS = {
  products: [
    { name:'FRANCE', reviews:5, stars:4.7, conv:'62%', ctr:'64%' },
    { name:'ITALY PRODUCT', reviews:2, stars:4.4, conv:'55%', ctr:'57%' },
    { name:'SPAIN GLOW KIT', reviews:2, stars:4.8, conv:'52%', ctr:'50%' },
  ],
  campaigns: [
    { name:'SPAIN', reviews:4, stars:4.6, conv:'60%', ctr:'62%' },
    { name:'Australia Campaign', reviews:3, stars:4.5, conv:'56%', ctr:'55%' },
    { name:'Cashback Test - Husain', reviews:2, stars:4.7, conv:'51%', ctr:'47%' },
  ],
};
const AN_MARKETS = [
  { name:'Amazon India', share:50, routed:3, ctr:'71%', stars:4.6, c:'#F59E0B' },
  { name:'Flipkart', share:17, routed:1, ctr:'58%', stars:4.5, c:'#0E9AD6' },
  { name:'Amazon.com', share:17, routed:1, ctr:'55%', stars:4.7, c:'#27B079' },
  { name:'Own website', share:16, routed:1, ctr:'49%', stars:4.4, c:'#6C57E0' },
];

function AnKpi({ lb, v, sub, tone, tip }) {
  return (
    <Card className="p-5">
      <p className="text-[11.5px] font-semibold uppercase tracking-wider text-ink-muted flex items-center gap-1.5">{lb}{tip && <InfoTip text={tip}/>}</p>
      <p className="text-[26px] font-extrabold text-ink mt-1.5 leading-none">{v}</p>
      {sub && <p className={"text-[11.5px] mt-1.5 font-semibold "+(tone==='up'?'text-green-600':tone==='warn'?'text-amber-600':'text-ink-soft')}>{sub}</p>}
    </Card>
  );
}

function AnLineChart() {
  const max = Math.max(...AN_SERIES);
  const W=640, H=140, step=W/(AN_SERIES.length-1);
  const pts = AN_SERIES.map((v,i)=>[i*step, H - (v/max)*(H-10)]);
  const path = pts.map((p,i)=>(i?'L':'M')+p[0].toFixed(1)+' '+p[1].toFixed(1)).join(' ');
  return (
    <svg viewBox={`0 0 ${W} ${H+8}`} className="w-full h-36" preserveAspectRatio="none">
      <path d={path+` L ${W} ${H+8} L 0 ${H+8} Z`} fill="var(--accent)" opacity="0.08"></path>
      <path d={path} fill="none" stroke="var(--accent)" strokeWidth="2.5" strokeLinecap="round"></path>
    </svg>
  );
}

function AnOverview() {
  return (
    <div className="space-y-5">
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <AnKpi lb="Reviews this month" v="8" sub="↑ vs 5 in June" tone="up" tip="Internal reviews collected on your claim pages in the current billing month."/>
        <AnKpi lb="Average rating" v="4.6 ★" sub="across 8 reviews" tip="Mean star rating of all internal reviews this month."/>
        <AnKpi lb="Claim → review" v="56%" sub="16 claims · 9 reviews" tip="Share of completed claims that ended with a written review."/>
        <AnKpi lb="Marketplace CTR" v="67%" sub="of reviewers clicked through" tip="Reviewers who clicked through to an external marketplace after their internal review. Posting can’t be verified — this is a proxy."/>
      </div>
      <div className="grid lg:grid-cols-[1fr_320px] gap-4 items-start">
        <Card className="p-5">
          <div className="flex items-center justify-between">
            <h3 className="text-[15px] font-bold text-ink flex items-center gap-2">Review velocity <InfoTip text="Reviews collected per day over the last 30 days."/></h3>
            <span className="text-[11.5px] text-ink-soft">Last 30 days · 9 reviews</span>
          </div>
          <div className="mt-4"><AnLineChart/></div>
        </Card>
        <Card className="p-5">
          <h3 className="text-[15px] font-bold text-ink flex items-center gap-2">Rating distribution <InfoTip text="Breakdown of star ratings. Low-star feedback stays internal — that’s your negative-review capture."/></h3>
          <div className="mt-4 space-y-2.5">
            {AN_STARS.map(([s,n])=>(
              <div key={s} className="flex items-center gap-2.5">
                <span className="w-7 text-[12px] font-bold text-ink whitespace-nowrap">{s}★</span>
                <div className="flex-1 h-2.5 rounded-full bg-surface-input overflow-hidden">
                  <div className="h-full rounded-full" style={{width:(n/5*100)+'%', background: s>=4 ? 'var(--accent)' : s===3 ? '#F59E0B' : '#E05252'}}></div>
                </div>
                <span className="w-7 text-right text-[12px] font-semibold text-ink-muted">{n}</span>
              </div>
            ))}
          </div>
          <p className="text-[11.5px] text-ink-soft mt-4 pt-3 border-t border-line/70"><b className="text-ink">2 low-star reviews</b> captured privately — never routed to marketplaces.</p>
        </Card>
      </div>
      <Card className="p-5">
        <div className="flex items-center justify-between flex-wrap gap-2">
          <h3 className="text-[15px] font-bold text-ink flex items-center gap-2">Plan usage <InfoTip text="How fast you’re using this month’s review quota, with a projection to month end."/></h3>
          <span className="text-[12px] text-ink-muted">8 of 10 reviews used · resets 1 Aug</span>
        </div>
        <div className="mt-3 h-3 rounded-full bg-surface-input overflow-hidden relative">
          <div className="h-full rounded-full" style={{width:'80%',background:'linear-gradient(90deg,var(--accent),var(--accent-dark))'}}></div>
          <div className="absolute top-0 bottom-0 w-px bg-amber-500" style={{left:'97%'}} title="Projected month-end: 11"></div>
        </div>
        <p className="text-[12px] text-amber-700 font-semibold mt-2">Projected 11 by month end — over your Free plan’s 10. Upgrade or grab a top-up pack to avoid a mid-month stop.</p>
      </Card>
    </div>
  );
}

function AnFunnel() {
  const top = AN_FUNNEL[0].v;
  return (
    <Card className="p-6">
      <div className="flex items-center justify-between flex-wrap gap-2">
        <h3 className="text-[15px] font-bold text-ink flex items-center gap-2">Customer journey <InfoTip text="Every stage from the QR scan to the marketplace click, with drop-off between steps."/></h3>
        <span className="text-[11.5px] text-ink-soft">Last 30 days · all campaigns</span>
      </div>
      <div className="mt-5 space-y-1.5">
        {AN_FUNNEL.map((s,i)=>{
          const prev = i ? AN_FUNNEL[i-1].v : s.v;
          const drop = i ? Math.round((1 - s.v/prev)*100) : null;
          return (
            <div key={s.lb}>
              {drop !== null && <p className="text-[10.5px] font-semibold text-ink-soft pl-1 py-0.5">↓ {100-drop}% carried over{drop>0 && ` · ${drop}% drop`}</p>}
              <div className="flex items-center gap-3">
                <div className="flex-1 h-9 rounded-lg bg-surface-input overflow-hidden">
                  <div className="h-full rounded-lg flex items-center px-3 gap-2 min-w-fit" style={{width:(s.v/top*100)+'%', background:`linear-gradient(90deg, var(--accent), var(--accent-dark))`, opacity:1-(i*0.09)}}>
                    <span className="text-[12px] font-bold text-white whitespace-nowrap">{s.lb}</span>
                  </div>
                </div>
                <span className="w-14 text-right text-[13.5px] font-extrabold text-ink">{s.v.toLocaleString()}</span>
                <InfoTip text={s.tip}/>
              </div>
            </div>
          );
        })}
      </div>
      <p className="text-[11.5px] text-ink-soft mt-5 pt-4 border-t border-line/70">“Clicked to marketplace” is the strongest available signal — marketplaces don’t confirm postings, so we never report “reviews posted”.</p>
    </Card>
  );
}

function AnTable({ title, tip, rows, nameLb }) {
  return (
    <Card>
      <div className="px-5 pt-5 pb-1"><h3 className="text-[15px] font-bold text-ink flex items-center gap-2">{title} <InfoTip text={tip}/></h3></div>
      <div className="grid text-[10.5px] font-bold uppercase tracking-wider text-ink-soft px-5 py-2.5 border-b border-line" style={{gridTemplateColumns:'1.8fr 90px 90px 110px 130px'}}>
        <span>{nameLb}</span><span className="text-right">Reviews</span><span className="text-right">Avg ★</span><span className="text-right">Claim → review</span><span className="text-right">Marketplace CTR</span>
      </div>
      {rows.map(r=>(
        <div key={r.name} className="grid items-center px-5 py-3 border-b border-line/60 last:border-0 text-[13px]" style={{gridTemplateColumns:'1.8fr 90px 90px 110px 130px'}}>
          <span className="font-bold text-ink truncate pr-2">{r.name}</span>
          <span className="text-right font-semibold text-ink">{r.reviews}</span>
          <span className="text-right text-ink">{r.stars}</span>
          <span className="text-right text-ink-muted">{r.conv}</span>
          <span className="text-right font-semibold acc-text">{r.ctr}</span>
        </div>
      ))}
    </Card>
  );
}

function AnMarkets() {
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {AN_MARKETS.map(m=>(
          <Card key={m.name} className="p-5">
            <div className="flex items-center gap-2"><span className="w-2 h-2 rounded-full" style={{background:m.c}}></span><span className="text-[12px] font-semibold text-ink-muted">{m.name}</span></div>
            <p className="text-[24px] font-extrabold text-ink mt-2 leading-none">{m.ctr}</p>
            <p className="text-[11.5px] text-ink-muted mt-1.5">click-through · {m.routed} routed · {m.stars} ★</p>
          </Card>
        ))}
      </div>
      <Card className="p-5">
        <h3 className="text-[15px] font-bold text-ink flex items-center gap-2">Where reviewers are routed <InfoTip text="Share of marketplace clicks by destination — tells you which channel your inserts feed most."/></h3>
        <div className="mt-4 flex h-4 rounded-full overflow-hidden">
          {AN_MARKETS.map(m=><div key={m.name} style={{width:m.share+'%', background:m.c}} title={m.name+' '+m.share+'%'}></div>)}
        </div>
        <div className="mt-3 flex flex-wrap gap-x-5 gap-y-1.5">
          {AN_MARKETS.map(m=>(
            <span key={m.name} className="inline-flex items-center gap-1.5 text-[12px] text-ink-muted"><span className="w-2 h-2 rounded-full" style={{background:m.c}}></span>{m.name} · <b className="text-ink">{m.share}%</b></span>
          ))}
        </div>
      </Card>
    </div>
  );
}

function MergedDashboard({ onNav = ()=>{}, newSeller = false }) {
  const [tab, setTab] = React.useState('overview');
  return (
    <>
      <PageHeader title="Dashboard" info="Your home base and analytics in one place — how the review engine performs, funnel drop-offs, and which products, campaigns and marketplaces earn the most."/>
      <div className="px-7 py-6 space-y-5">
        <div className="inline-flex p-1 rounded-xl bg-surface-subtle border border-line gap-1">
          {AN_TABS.map(t=>(
            <button key={t.id} onClick={()=>setTab(t.id)} className={"px-4 py-2 rounded-lg text-[13px] font-bold transition-colors "+(tab===t.id?'bg-white text-ink shadow-soft':'text-ink-muted hover:text-ink')}>{t.label}</button>
          ))}
        </div>
        {tab==='overview' && (
          <div className="space-y-5">
            {newSeller && window.SetupChecklist && <SetupChecklist onNav={onNav}/>}
            <AnOverview/>
            {window.ActivityFeed && <ActivityFeed onNav={onNav}/>}
          </div>
        )}
        {tab==='funnel'   && <AnFunnel/>}
        {tab==='items'    && <div className="space-y-4"><AnTable title="By product" tip="Products ranked by reviews collected this month." rows={AN_ITEMS.products} nameLb="Product"/><AnTable title="By campaign" tip="Campaigns ranked by reviews collected this month." rows={AN_ITEMS.campaigns} nameLb="Campaign"/></div>}
        {tab==='markets'  && <AnMarkets/>}
      </div>
    </>
  );
}

window.Dashboard = MergedDashboard;
MergedDashboard.v2 = true;
window.AnalyticsPage = MergedDashboard; /* legacy route alias */
