/* ─── Dashboard — v2 redesign ────────────────────────────────────────────────
   Plan banner → metric cards w/ global period switch + sparklines →
   reviews chart + conversion funnel → activity feed. Empty state collapses
   to a 3-step setup checklist. Overrides window.Dashboard. Demo data invented. */

const DASH_SERIES = { // per-day series for the last 30 days
  reviews:[2,3,1,4,2,5,3,4,6,3,2,5,7,4,3,6,5,8,4,6,7,5,9,6,8,7,10,8,9,11],
  delivered:[1,3,1,3,2,4,3,3,5,3,2,4,6,4,3,5,4,7,4,5,6,5,7,5,7,6,8,7,8,9],
  visits: [9,11,8,13,10,16,12,15,18,12,10,17,20,15,12,19,17,24,15,19,22,17,26,19,24,22,30,25,28,32],
  rating: [4.2,4.5,4.0,4.6,4.3,4.7,4.4,4.5,4.8,4.4,4.2,4.6,4.8,4.5,4.3,4.7,4.6,4.9,4.4,4.6,4.7,4.5,4.9,4.6,4.8,4.7,4.9,4.7,4.8,4.9],
};
const DASH_PERIODS = { 'Today':1, '7 days':7, '30 days':30 };
const sum = a => a.reduce((x,y)=>x+y,0);
const slice7 = (a,n) => a.slice(-n);
const pct = (a,b) => b ? Math.round(((a-b)/b)*100) : 0;

function Sparkline({ data, color }) {
  const w=110, h=30, max=Math.max(...data,1);
  const pts = data.map((v,i)=>`${(i/(data.length-1))*w},${h - (v/max)*(h-4) - 2}`).join(' ');
  return (
    <svg width={w} height={h} className="block">
      <polyline points={pts} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" opacity=".9"/>
    </svg>
  );
}

function DashMetric({ label, value, delta, series, color }) {
  const up = delta >= 0;
  return (
    <Card className="p-5">
      <p className="text-[11.5px] font-bold uppercase tracking-[0.1em] text-ink-muted">{label}</p>
      <div className="mt-2 flex items-end justify-between gap-2">
        <div>
          <p className="text-[28px] font-extrabold tracking-tight text-ink leading-none">{value.toLocaleString()}</p>
          {delta === null
            ? <p className="mt-2 text-[11.5px] font-medium text-ink-soft">last 30 days</p>
            : <p className={"mt-2 text-[11.5px] font-bold inline-flex items-center gap-1 "+(up?"text-green-600":"text-rose-600")}>
                <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" style={up?{}:{transform:'rotate(180deg)'}}><path d="M12 19V5M6 11l6-6 6 6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                {Math.abs(delta)}% <span className="font-medium text-ink-soft">vs prev</span>
              </p>}
        </div>
        <Sparkline data={series} color={color}/>
      </div>
    </Card>
  );
}

function ReviewsChart({ days }) {
  const data = slice7(DASH_SERIES.reviews, Math.max(days,7));
  const w=560, h=180, max=Math.max(...data)+2;
  const x = i => (i/(data.length-1))*w;
  const y = v => h - (v/max)*(h-20) - 6;
  const line = data.map((v,i)=>`${x(i)},${y(v)}`).join(' ');
  const area = `0,${h} ${line} ${w},${h}`;
  return (
    <Card className="p-5 flex-1 min-w-0">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-[15px] font-bold text-ink flex items-center gap-2">Reviews over time <InfoTip text="Daily count of verified reviews collected through your campaigns in the selected period."/></h3>
          <p className="text-[12px] text-ink-muted mt-0.5">Last {Math.max(days,7)} days · {sum(data)} reviews</p>
        </div>
        <span className="inline-flex items-center gap-1.5 text-[11px] font-bold px-2.5 py-1 rounded-full bg-brand-50 text-brand"><span className="w-1.5 h-1.5 rounded-full bg-brand"></span>Reviews</span>
      </div>
      <svg viewBox={`0 0 ${w} ${h}`} className="w-full mt-4" preserveAspectRatio="none" style={{height:180}}>
        {[0.25,0.5,0.75].map(f=><line key={f} x1="0" x2={w} y1={h*f} y2={h*f} stroke="#ECE9E3" strokeWidth="1"/>)}
        <polygon points={area} fill="url(#dashGrad)" opacity=".35"/>
        <polyline points={line} fill="none" stroke="#0E9AD6" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
        <defs><linearGradient id="dashGrad" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="#0E9AD6"/><stop offset="100%" stopColor="#0E9AD6" stopOpacity="0"/></linearGradient></defs>
      </svg>
    </Card>
  );
}

function FunnelCard({ days }) {
  const n = Math.max(days,7);
  const visits = sum(slice7(DASH_SERIES.visits,n)), reviews = sum(slice7(DASH_SERIES.reviews,n)), delivered = sum(slice7(DASH_SERIES.delivered,n));
  const rows = [
    { label:'Claim page visits',    sub:'QR scans + link opens', v:visits,    color:'#0E9AD6' },
    { label:'Reviews submitted',    sub:'completed the claim',   v:reviews,   color:'#6C57E0' },
    { label:'Promotions delivered', sub:'reward sent',           v:delivered, color:'#27B079' },
  ];
  return (
    <Card className="p-5 w-full lg:w-[300px] shrink-0">
      <h3 className="text-[15px] font-bold text-ink flex items-center gap-2">Claim funnel <InfoTip text="How customers move from scanning your QR code to a delivered reward — spot where drop-offs happen."/></h3>
      <p className="text-[12px] text-ink-muted mt-0.5">Last {n} days</p>
      <div className="mt-4 space-y-3">
        {rows.map((r,i) => (
          <div key={r.label}>
            <div className="flex items-baseline justify-between text-[12.5px]">
              <span className="font-semibold text-ink">{r.label}</span>
              <span className="font-extrabold text-ink">{r.v.toLocaleString()}</span>
            </div>
            <p className="text-[10.5px] text-ink-soft">{r.sub}</p>
            <div className="mt-1.5 h-2.5 rounded-full bg-surface-input overflow-hidden">
              <div className="h-full rounded-full" style={{width:(r.v/rows[0].v*100)+'%', background:r.color}}></div>
            </div>
            {i < rows.length-1 && (
              <p className="text-[10.5px] text-ink-soft mt-1 text-right">{Math.round(rows[i+1].v/r.v*100)}% ↓</p>
            )}
          </div>
        ))}
      </div>
      <p className="mt-4 pt-3 border-t border-line/70 text-[11.5px] text-ink-muted"><span className="font-bold text-ink">{reviews - delivered}</span> reviews waiting for delivery — <span className="font-bold acc-text">clear them in Claim Center</span></p>
    </Card>
  );
}

const DASH_ACTIVITY = [
  { name:'Aisha K.',   product:'Brontix Wifi Router',      stars:5, mkt:'amazon',  time:'12 min ago' },
  { name:'Tom W.',     product:'Bedsure Queen Comforter',  stars:4, mkt:'amazon',  time:'1 hr ago' },
  { name:'Priya S.',   product:'Breast Pump First Cry',    stars:5, mkt:'firstcry',time:'3 hrs ago' },
  { name:'Marco D.',   product:'ITALY PRODUCT',            stars:5, mkt:'etsy',    time:'Yesterday' },
  { name:'Jess M.',    product:'UK testing',               stars:3, mkt:'ebay',    time:'Yesterday' },
];

function ActivityFeed({ onNav }) {
  return (
    <Card>
      <div className="px-5 py-4 flex items-center justify-between">
        <h3 className="text-[15px] font-bold text-ink flex items-center gap-2">Recent activity <InfoTip text="The latest customer actions across your campaigns — claims, reviews and reward deliveries."/></h3>
        <span className="flex items-center gap-3">
          <button onClick={()=>onNav('customers')} className="text-[12.5px] font-bold acc-text hover:opacity-80">View all →</button>
        </span>
      </div>
      <div className="divide-y divide-gray-100">
        {DASH_ACTIVITY.map((a,i) => (
          <div key={i} className="px-5 py-3 flex items-center gap-4 hover:bg-surface-subtle transition-colors">
            <span className="w-9 h-9 rounded-full text-white text-[12px] font-bold flex items-center justify-center shrink-0"
                  style={{background:`linear-gradient(135deg, hsl(${(i*67+30)%360},60%,60%), hsl(${(i*67+70)%360},55%,45%))`}}>{a.name[0]}</span>
            <div className="min-w-0 flex-1">
              <p className="text-[13px] text-ink truncate"><span className="font-bold">{a.name}</span> reviewed <span className="font-semibold">{a.product}</span></p>
              <p className="text-[11.5px] text-ink-soft mt-0.5">{a.time}</p>
            </div>
            <span className="hidden sm:flex items-center gap-0.5">{[1,2,3,4,5].map(s=><span key={s} className="text-[13px]" style={{color:s<=a.stars?'#F59E0B':'#E2E8F0'}}>★</span>)}</span>
            <MarketplaceLogos list={[a.mkt]}/>
          </div>
        ))}
      </div>
    </Card>
  );
}

function SetupChecklist({ onNav }) {
  const steps = [
    { n:1, label:'Add your first product',   d:'Connect it to your marketplaces', route:'product-add',      done:true },
    { n:2, label:'Create a promotion',       d:'The reward customers claim',      route:'promotion-create', done:false },
    { n:3, label:'Launch a campaign',        d:'Plug product + promotion, get your QR', route:'campaign-add', done:false },
  ];
  return (
    <Card className="p-6">
      <h3 className="text-[16px] font-bold text-ink">Get set up in 3 steps</h3>
      <p className="text-[12.5px] text-ink-muted mt-1">Finish setup to start collecting reviews — takes about 5 minutes.</p>
      <div className="mt-5 grid md:grid-cols-3 gap-4">
        {steps.map(s => (
          <button key={s.n} onClick={()=>onNav(s.route)}
            className={"text-left rounded-2xl border p-4 transition-all "+(s.done?"border-green-200 bg-green-50/50":"border-line bg-white hover:border-[var(--accent)] hover:shadow-soft")}>
            <span className={"w-8 h-8 rounded-full flex items-center justify-center text-[13px] font-bold "+(s.done?"bg-green-500 text-white":"acc-bg-soft acc-text")}>
              {s.done ? <svg width="13" height="13" viewBox="0 0 14 14" fill="none"><path d="M2.5 7l3 3 6-6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg> : s.n}
            </span>
            <p className="mt-3 text-[13.5px] font-bold text-ink">{s.label}</p>
            <p className="text-[12px] text-ink-muted mt-1">{s.d}</p>
            {!s.done && <p className="mt-2.5 text-[12px] font-bold acc-text">Start →</p>}
          </button>
        ))}
      </div>
    </Card>
  );
}

function DashboardV2({ onNav, newSeller=false }) {
  const [period, setPeriod] = React.useState('7 days');
  const n = DASH_PERIODS[period];
  const metric = (key) => {
    const cur = sum(slice7(DASH_SERIES[key], n));
    const prevSlice = DASH_SERIES[key].slice(-(n*2), -n);
    return { v:cur, d: prevSlice.length >= n ? pct(cur, sum(prevSlice) || 1) : null };
  };
  const customers = { v: Math.round(metric('reviews').v * 0.9), d: metric('reviews').d };
  const avgRating = (arr => arr.reduce((a,b)=>a+b,0)/arr.length)(slice7(DASH_SERIES.rating, Math.max(n,3)));
  const prevArr = DASH_SERIES.rating.slice(-(Math.max(n,3)*2), -Math.max(n,3));
  const prevRating = prevArr.length ? prevArr.reduce((a,b)=>a+b,0)/prevArr.length : avgRating;
  return (
    <>
      <PageHeader title="Dashboard" action={
        <div className="flex items-center gap-1 bg-surface-input rounded-xl p-1">
          {Object.keys(DASH_PERIODS).map(p => (
            <button key={p} onClick={()=>setPeriod(p)}
              className={"px-3.5 py-2 rounded-lg text-[12.5px] font-bold transition-colors "+(period===p?"bg-white text-ink shadow-sm":"text-ink-muted hover:text-ink")}>{p}</button>
          ))}
        </div>
      }/>
      <div className="px-7 py-6 space-y-5">
        {/* plan banner */}
        <div className="rounded-2xl bg-white border border-line shadow-card px-5 py-4 flex items-center justify-between gap-6 flex-wrap">
          <div className="flex items-center gap-4 min-w-0">
            <span className="w-11 h-11 rounded-xl flex items-center justify-center shrink-0 acc-bg-soft acc-text">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 2l2.4 7.4H22l-6 4.4 2.3 7.2L12 16.7 5.7 21l2.3-7.2-6-4.4h7.6z"/></svg>
            </span>
            <div className="min-w-0">
              <p className="text-[14px] font-bold text-ink">You're on the <span className="acc-text">Free</span> plan</p>
              <div className="flex items-center gap-2.5 mt-1.5">
                <div className="w-40 h-1.5 rounded-full bg-surface-input overflow-hidden">
                  <div className="h-full rounded-full" style={{width:'3.3%',background:'linear-gradient(90deg,var(--accent),var(--accent-dark))'}}></div>
                </div>
                <span className="text-[12px] text-ink-muted font-medium">1 / 30 reviews used</span>
              </div>
            </div>
          </div>
          <button onClick={() => window.__openPricing ? window.__openPricing() : onNav('settings','billing')}
            className="text-[13px] font-bold acc-text hover:opacity-80 inline-flex items-center gap-1">
            Upgrade plan
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
        </div>

        {newSeller ? (
          <SetupChecklist onNav={onNav}/>
        ) : (
          <>
            <div className="grid grid-cols-2 xl:grid-cols-4 gap-4">
              <DashMetric label="Reviews" {...{value:metric('reviews').v, delta:metric('reviews').d}} series={slice7(DASH_SERIES.reviews,14)} color="#0E9AD6"/>
              <Card className="p-5">
                <p className="text-[11.5px] font-bold uppercase tracking-[0.1em] text-ink-muted">Avg rating</p>
                <div className="mt-2 flex items-end justify-between gap-2">
                  <div>
                    <p className="text-[28px] font-extrabold tracking-tight text-ink leading-none">{avgRating.toFixed(1)} <span className="text-[18px]" style={{color:'#F59E0B'}}>★</span></p>
                    <p className={"mt-2 text-[11.5px] font-bold "+(avgRating>=prevRating?"text-green-600":"text-rose-600")}>{avgRating>=prevRating?'+':''}{(avgRating-prevRating).toFixed(1)} <span className="font-medium text-ink-soft">vs prev</span></p>
                  </div>
                  <Sparkline data={slice7(DASH_SERIES.rating,14)} color="#F59E0B"/>
                </div>
              </Card>
              <DashMetric label="Promos delivered" {...{value:metric('delivered').v, delta:metric('delivered').d}} series={slice7(DASH_SERIES.delivered,14)} color="#27B079"/>
              <DashMetric label="New customers" {...{value:customers.v, delta:customers.d}} series={slice7(DASH_SERIES.reviews,14).map(v=>Math.max(1,v-1))} color="#6C57E0"/>
            </div>
            <div className="flex flex-col lg:flex-row gap-5 items-stretch">
              <ReviewsChart days={n}/>
              <FunnelCard days={n}/>
            </div>
            {window.ReviewHealthCard && (
              <div className="flex flex-col lg:flex-row gap-5 items-stretch">
                <ReviewHealthCard onNav={onNav}/>
                <InterceptCard/>
              </div>
            )}
            <ActivityFeed onNav={onNav}/>
          </>
        )}
      </div>
    </>
  );
}

window.Dashboard = DashboardV2;
DashboardV2.v2 = true;
Object.assign(window, { ActivityFeed, SetupChecklist });
