// ───────────────────────────────────────────────────────────
// Market Share Dashboard — live Google Sheet data
// ───────────────────────────────────────────────────────────

const { useState: useStateD, useEffect: useEffectD, useMemo: useMemoD, useCallback } = React;
const Sheet = window.MarketShareSheet;

// ─── Status pill (live / cached / loading / error) ───────
function StatusPill({ status, ts, onRefresh, loading }) {
  const variants = {
    live: { label: 'Live data', dot: '#1F9D6B', bg: 'rgba(31,157,107,0.12)', fg: '#1F9D6B' },
    cached: { label: 'Cached', dot: '#E0A93B', bg: 'rgba(224,169,59,0.14)', fg: '#A57318' },
    error: { label: 'Sheet offline', dot: '#D14343', bg: 'rgba(209,67,67,0.12)', fg: '#D14343' },
    loading: { label: 'Fetching…', dot: '#00BBEA', bg: 'rgba(0,187,234,0.12)', fg: '#0090B5' }
  };
  const v = variants[status] || variants.loading;
  return (
    <div className="ms-status">
      <span className="ms-status-pill" style={{ background: v.bg, color: v.fg }}>
        <span className="ms-status-dot" style={{ background: v.dot }} />
        {v.label}
      </span>
      {ts && <span className="ms-status-ts">Updated {new Date(ts).toLocaleString()}</span>}
      <button className="ms-refresh" onClick={onRefresh} disabled={loading} title="Refresh from Google Sheet">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ animation: loading ? 'msSpin 1s linear infinite' : 'none' }}>
          <path d="M21 12a9 9 0 0 1-15.36 6.36M3 12a9 9 0 0 1 15.36-6.36" />
          <path d="M21 4v5h-5M3 20v-5h5" />
        </svg>
        Refresh
      </button>
    </div>);

}

// ─── KPI Card (lighter version) ──────────────────────────
function KpiCardLive({ label, value, unit, delta, deltaLabel, note, accent = '#00BBEA', sparkData }) {
  const dUp = delta != null && delta > 0;
  const dDown = delta != null && delta < 0;
  return (
    <div className="ms-kpi">
      <div className="ms-kpi-label">{label}</div>
      <div className="ms-kpi-value">
        {value}
        {unit && <span className="ms-kpi-suf">{unit}</span>}
      </div>
      <div className="ms-kpi-foot">
        {delta != null &&
        <span className={`ms-kpi-delta ms-kpi-delta--${dUp ? 'positive' : dDown ? 'negative' : 'neutral'}`}>
            <svg width="10" height="10" viewBox="0 0 10 10">
              {dUp && <path d="M5 1.5 L9 7 L1 7 Z" fill="currentColor" />}
              {dDown && <path d="M5 8.5 L1 3 L9 3 Z" fill="currentColor" />}
            </svg>
            {delta > 0 ? '+' : ''}{delta.toFixed(1)}{unit && (unit === '%' || unit === 'pp') ? unit : ''}
          </span>
        }
        {deltaLabel && <span className="ms-kpi-delta-label">{deltaLabel}</span>}
      </div>
      {sparkData && sparkData.length > 1 &&
      <div className="ms-kpi-spark"><SparklineC data={sparkData} color={accent} width={140} height={32} /></div>
      }
      {note && <div className="ms-kpi-note">{note}</div>}
    </div>);

}

// ─── Section header ──────────────────────────────────────
function SectionH({ eyebrow, title, hint, right }) {
  return (
    <div className="ms-section-head">
      <div>
        {eyebrow && <div className="ms-section-eyebrow">{eyebrow}</div>}
        <h2 className="ms-section-title">{title}</h2>
        {hint && <div className="ms-section-hint">{hint}</div>}
      </div>
      {right && <div className="ms-section-right">{right}</div>}
    </div>);

}

// ─── Loading skeleton ────────────────────────────────────
function Skel({ height = 100 }) {
  return <div className="ms-skel" style={{ height }} />;
}

// ─── Error banner ────────────────────────────────────────
function ErrorBanner({ message, onRetry, hasCached }) {
  return (
    <div className="ms-errbanner">
      <div className="ms-errbanner-icon">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 3 L22 20 H2 Z" strokeLinejoin="round" /><path d="M12 10 V14 M12 17 V17.5" strokeLinecap="round" /></svg>
      </div>
      <div className="ms-errbanner-body">
        <div className="ms-errbanner-title">Couldn't reach the Google Sheet</div>
        <div className="ms-errbanner-msg">{message}</div>
        {hasCached && <div className="ms-errbanner-msg" style={{ marginTop: 4, opacity: 0.85 }}>Showing the most recent cached snapshot.</div>}
      </div>
      <button className="ms-errbanner-btn" onClick={onRetry}>Retry</button>
    </div>);

}

// ─── Helpers ────────────────────────────────────────────
const CHANNEL_DEFS = [
{ id: 'organic', label: 'Organic search', color: '#002147' },
{ id: 'paid', label: 'Paid search', color: '#00BBEA' },
{ id: 'direct', label: 'Direct', color: '#CBFF00' },
{ id: 'referral', label: 'Referral', color: '#7B5EA7' },
{ id: 'social', label: 'Social', color: '#E07A5F' }];


function decorateRows(rows) {
  return rows.map((r, i) => ({ ...r, ...Sheet.configForDomain(r.domain, i) }));
}

// ─── Main Dashboard ──────────────────────────────────────
function Dashboard() {
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "dark": false,
    "density": "comfortable",
    "showChannels": true,
    "showAbsolute": true,
    "showBranded": true,
    "showOrganic": true,
    "showPaid": true,
    "showLeads": true
  } /*EDITMODE-END*/;

  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [data, setData] = useStateD(null);
  const [status, setStatus] = useStateD('loading'); // loading | live | cached | error
  const [error, setError] = useStateD(null);
  const [loading, setLoading] = useStateD(true);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const fresh = await Sheet.fetchAll();
      Sheet.saveCache(fresh);
      setData(fresh);
      setStatus('live');
      setError(null);
    } catch (e) {
      const cached = Sheet.loadCache();
      if (cached && cached.data) {
        setData(cached.data);
        setStatus('cached');
      } else {
        setStatus('error');
      }
      setError(e.message || String(e));
    } finally {
      setLoading(false);
    }
  }, []);

  useEffectD(() => {load();}, [load]);

  // Decorate rows w/ display config
  const decorated = useMemoD(() => {
    if (!data) return null;
    return {
      ...data,
      sectionA: decorateRows(data.sectionA),
      sectionB2: decorateRows(data.sectionB2 || []),
      sectionB: decorateRows(data.sectionB),
      sectionC: decorateRows(data.sectionC),
      sectionD: decorateRows(data.sectionD),
      sectionE: decorateRows(data.sectionE),
      sectionF: decorateRows(data.sectionF || [])
    };
  }, [data]);

  // Compute KPIs from Section A
  const kpis = useMemoD(() => {
    if (!decorated) return null;
    const us = decorated.sectionA.find((r) => r.isUs);
    const sorted = [...decorated.sectionA].sort((a, b) => (b.marketPct || 0) - (a.marketPct || 0));
    const rank = us ? sorted.findIndex((r) => r.domain === us.domain) + 1 : null;
    const leader = sorted[0];
    const totalVisits = decorated.sectionA.reduce((a, r) => a + (r.visits || 0), 0);
    const usD = decorated.sectionD?.find((r) => r.isUs);
    const usE = decorated.sectionE?.find((r) => r.isUs);
    const usC = decorated.sectionC?.find((r) => r.isUs);
    return {
      share: us?.marketPct,
      visits: us?.visits,
      rank,
      gap: us && leader ? leader.marketPct - us.marketPct : null,
      totalMarket: totalVisits,
      kwsTop3: usD?.kwsTop3,
      impShare: usE?.impShare,
      brandedRatio: usC?.brandedShareOwn,
      leaderName: leader?.name || leader?.domain
    };
  }, [decorated]);

  return (
    <div className={`ms-app ms-app--${tweaks.dark ? 'dark' : 'light'} ms-density--${tweaks.density}`}>
      {/* Header */}
      <header className="ms-header">
        <div className="ms-header-left">
          <img
            src={tweaks.dark ? 'assets/logo-horizontal-dark.png' : 'assets/logo-horizontal-light.png'}
            alt="CarBrain" className="ms-logo" style={{ height: "100px", width: "234.734px" }} />
          
          <div className="ms-header-divider" />
          <div className="ms-header-titles">
            <div className="ms-header-eyebrow">Competitive Intelligence</div>
            <h1 className="ms-header-title">Market Share Report</h1>
            {decorated &&
            <div className="ms-header-month">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ marginRight: 5, verticalAlign: '-2px' }}><rect x="3" y="5" width="18" height="16" rx="2" /><path d="M3 10h18M9 3v4M15 3v4" /></svg>
                Analysis period: <strong>{decorated.analysisMonth}</strong>
              </div>
            }
          </div>
        </div>
        <div className="ms-header-right">
          <StatusPill
            status={loading ? 'loading' : status}
            ts={data?.fetchedAt}
            onRefresh={load}
            loading={loading} />
          
        </div>
      </header>

      {/* Error banner */}
      {error && status !== 'live' &&
      <section className="ms-section">
          <ErrorBanner message={error} onRetry={load} hasCached={!!data} />
        </section>
      }

      {/* Loading skeleton */}
      {!data &&
      <section className="ms-section">
          <div className="ms-kpi-grid">
            {Array.from({ length: 8 }).map((_, i) => <Skel key={i} height={140} />)}
          </div>
          <div className="ms-section-grid ms-section-grid--7-5" style={{ marginTop: 20 }}>
            <Skel height={420} />
            <Skel height={420} />
          </div>
        </section>
      }

      {decorated &&
      <>
          {/* KPI Row */}
          <section className="ms-section">
            <div className="ms-kpi-grid">
              <KpiCardLive
              label="Market share"
              value={kpis.share != null ? kpis.share.toFixed(1) : '—'}
              unit="%"
              deltaLabel={kpis.leaderName ? `Leader: ${kpis.leaderName}` : ''}
              note="Share of total market visits"
              accent="#00BBEA" />
            
              <KpiCardLive
              label="Visits captured"
              value={fmtNumLive(kpis.visits)}
              deltaLabel="this period"
              note={`Of ${fmtNumLive(kpis.totalMarket)} total market`} />
            
              <KpiCardLive
              label="Market rank"
              value={kpis.rank != null ? `#${kpis.rank}` : '—'}
              note={`Out of ${decorated.sectionA.length} buyers`} />
            
              <KpiCardLive
              label="Gap to leader"
              value={kpis.gap != null ? kpis.gap.toFixed(1) : '0.0'}
              unit="pp"
              note={kpis.gap === 0 ? 'You are the leader' : `vs. ${kpis.leaderName}`} />
            
              <KpiCardLive
              label="KWs in top-3"
              value={fmtNumLive(kpis.kwsTop3)}
              note="Organic SEO presence" />
            
              <KpiCardLive
              label="Impression share"
              value={kpis.impShare != null ? kpis.impShare.toFixed(1) : 'n/a'}
              unit={kpis.impShare != null ? '%' : ''}
              note={kpis.impShare != null ? 'Paid search SOV' : 'CarBrain not in paid SOV set'} />
            
              <KpiCardLive
              label="Branded ratio"
              value={kpis.brandedRatio != null ? kpis.brandedRatio.toFixed(0) : '—'}
              unit="%"
              note="Branded / total search" />
            
              <KpiCardLive
              label="Buyers tracked"
              value={decorated.sectionA.length}
              note="In competitive set" />
            
            </div>
          </section>

          {/* Section A: Market share + Donut */}
          <section className="ms-section ms-section-grid ms-section-grid--7-5">
            <div className="ms-card">
              <SectionH
              eyebrow="Section A"
              title="Traffic share by buyer"
              hint="Total visits captured this period and resulting % of market" />
            
              <RankBars
              rows={decorated.sectionA}
              valueKey="marketPct"
              valueLabel="% of market" />
            
              <div className="ms-stat-strip">
                <div>
                  <div className="ms-stat-label">Total market visits</div>
                  <div className="ms-stat-val">{fmtNumLive(kpis.totalMarket)}</div>
                </div>
                <div>
                  <div className="ms-stat-label">Buyers</div>
                  <div className="ms-stat-val">{decorated.sectionA.length}</div>
                </div>
                <div>
                  <div className="ms-stat-label">Period</div>
                  <div className="ms-stat-val" style={{ fontSize: 16 }}>{decorated.analysisMonth}</div>
                </div>
              </div>
            </div>
            <div className="ms-card">
              <SectionH eyebrow="Distribution" title="Share of market" hint="Slice = buyer's share of total market traffic" />
              <DonutShare rows={decorated.sectionA} valueKey="marketPct" />
            </div>
          </section>

          {/* Section B2 — Absolute channel visits */}
          {tweaks.showAbsolute &&
        <section className="ms-section">
              <div className="ms-card">
                <SectionH
              eyebrow="Section B2"
              title="Absolute channel visits"
              hint="Estimated raw visits per channel (total visits × channel %). Shows true magnitude — the same channel % means very different volume across competitors." />
            
                <ChannelAbsolute rows={decorated.sectionB2} channels={CHANNEL_DEFS} />
              </div>
            </section>
        }

          {/* Section B3: Channel stack */}
          {tweaks.showChannels &&
        <section className="ms-section">
              <div className="ms-card">
                <SectionH
              eyebrow="Section B3"
              title="Channel mix per buyer"
              hint="How each competitor's traffic breaks down across channels — read horizontally" />
            
                <ChannelStack rows={decorated.sectionB} channels={CHANNEL_DEFS} />
              </div>
            </section>
        }

          {/* Section C: Branded vs Non-Branded */}
          {tweaks.showBranded &&
        <section className="ms-section">
              <div className="ms-card">
                <SectionH
              eyebrow="Section C"
              title="Branded vs. non-branded search"
              hint="Of each buyer's search traffic, how much comes from people typing their brand name vs. category keywords" />
            
                <BrandedSplit rows={decorated.sectionC} />
                <div style={{ marginTop: 24, paddingTop: 24, borderTop: '1px solid var(--ms-border)' }}>
                  <div style={{ marginBottom: 16 }}>
                    <div className="ms-section-eyebrow">Absolute volume</div>
                    <h3 style={{ fontFamily: 'var(--cb-font-display)', fontSize: 18, color: 'var(--ms-fg-1)', margin: '0 0 4px 0' }}>
                      Branded vs non-branded — visit counts
                    </h3>
                    <div className="ms-section-hint">
                      Same data in absolute numbers. Reveals true magnitude — a high branded % on a small base is very different from a moderate % on a large one.
                    </div>
                  </div>
                  <BrandedAbsolute rows={decorated.sectionC} />
                </div>
              </div>
            </section>
        }

          {/* Section D: Organic SEMrush */}
          {tweaks.showOrganic &&
        <section className="ms-section">
              <div className="ms-card">
                <SectionH
              eyebrow="Section D"
              title="Organic search performance (SEMrush)"
              hint="Lower avg. position is better; higher counts and rates are better" />
            
                <OrganicTable rows={decorated.sectionD} />
              </div>
            </section>
        }

          {/* Section E: Paid SOV */}
          {tweaks.showPaid &&
        <section className="ms-section">
              <div className="ms-card">
                <SectionH
              eyebrow="Section E"
              title="Paid search Share of Voice"
              hint="Auction-level metrics from Google Ads — head-to-head competitive view" />
            
                <PaidGrid rows={decorated.sectionE} />
              </div>
            </section>
        }

          {/* Section F: Estimated lead share */}
          {tweaks.showLeads && decorated.sectionF?.length > 0 &&
        <section className="ms-section">
              <div className="ms-card">
                <SectionH
              eyebrow="Section F"
              title="Estimated lead share"
              hint="Modeled leads = traffic × CVR. Translates audience-level visibility into business outcomes." />
            
                <LeadShare
                  rows={decorated.sectionF}
                  paidRows={decorated.sectionE}
                  brandedRows={decorated.sectionC}
                />
              </div>
            </section>
        }

          <footer className="ms-footer">
            <div>Source: <strong>Google Sheet · Dashboard tab</strong> · {decorated.analysisMonth}</div>
            <div>Confidential · Internal use only</div>
          </footer>
        </>
      }

      {/* Tweaks Panel */}
      <TweaksPanel title="Tweaks">
        <TweakSection title="Theme">
          <TweakToggle label="Dark mode" checked={tweaks.dark} onChange={(v) => setTweak('dark', v)} />
          <TweakRadio
            label="Density" value={tweaks.density}
            onChange={(v) => setTweak('density', v)}
            options={[
            { value: 'compact', label: 'Compact' },
            { value: 'comfortable', label: 'Comfy' },
            { value: 'spacious', label: 'Spacious' }]
            } />
          
        </TweakSection>
        <TweakSection title="Sections">
          <TweakToggle label="Section B2 — Absolute" checked={tweaks.showAbsolute} onChange={(v) => setTweak('showAbsolute', v)} />
          <TweakToggle label="Section B — Channels" checked={tweaks.showChannels} onChange={(v) => setTweak('showChannels', v)} />
          <TweakToggle label="Section C — Branded" checked={tweaks.showBranded} onChange={(v) => setTweak('showBranded', v)} />
          <TweakToggle label="Section D — Organic" checked={tweaks.showOrganic} onChange={(v) => setTweak('showOrganic', v)} />
          <TweakToggle label="Section E — Paid" checked={tweaks.showPaid} onChange={(v) => setTweak('showPaid', v)} />
          <TweakToggle label="Section F — Leads" checked={tweaks.showLeads} onChange={(v) => setTweak('showLeads', v)} />
        </TweakSection>
        <TweakSection title="Data">
          <TweakButton label="Refresh from Sheet" onClick={load} />
        </TweakSection>
      </TweaksPanel>
    </div>);

}

ReactDOM.createRoot(document.getElementById('root')).render(<Dashboard />);