// 1Radar v3 — Brand Detail (customisable dashboard)

const BRAND_DETAIL_SECTIONS_DEFAULT = {
  activeAds:   true,
  fbPages:     true,
  avgFbLikes:  true,
  trustpilot:  true,
  sales:       true,
  estSpend:    true,
  visitors:    true,
  topCountry:  true,
  topProducts: true,
  topAds:      true,
};

const BRAND_DETAIL_SECTION_OPTIONS = [
  { id: 'activeAds',   label: 'Active / Total ads',     icon: 'sparkles' },
  { id: 'fbPages',     label: 'Facebook pages',         icon: 'globe' },
  { id: 'avgFbLikes',  label: 'Avg. FB page likes',     icon: 'heart' },
  { id: 'trustpilot',  label: 'Trustpilot rating',      icon: 'star' },
  { id: 'sales',       label: 'Sales last 30 days',     icon: 'wallet' },
  { id: 'estSpend',    label: 'Est. ad spend',          icon: 'trend-up' },
  { id: 'visitors',    label: 'Visitors last 6 months', icon: 'users' },
  { id: 'topCountry',  label: 'Top country',            icon: 'flag' },
  { id: 'topProducts', label: 'Top 3 products',         icon: 'shop' },
  { id: 'topAds',      label: 'Top 3 ads',              icon: 'copy' },
];

const fmtBrandNum = (n) => {
  if (n == null) return '—';
  if (n >= 1_000_000) return (n / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M';
  if (n >= 1_000)     return (n / 1_000).toFixed(1).replace(/\.0$/, '') + 'K';
  return n.toLocaleString();
};

// ── Tiny stat card ───────────────────────────────────────────────────────────
const StatCardBD = ({ icon, label, value, sub, children }) => (
  <div className="card" style={{
    flex: 1, minWidth: 0, padding: '16px 18px',
    display: 'flex', flexDirection: 'column', gap: 6,
  }}>
    <div style={{
      display: 'flex', alignItems: 'center', gap: 5,
      fontSize: 11, fontWeight: 600, color: 'var(--text-faint)',
      textTransform: 'uppercase', letterSpacing: '0.05em',
    }}>
      {icon && <Icon name={icon} size={12}/>}
      {label}
    </div>
    <div style={{
      fontSize: 28, fontWeight: 700, fontFamily: 'var(--font-mono)',
      color: 'var(--text)', lineHeight: 1.1,
    }}>
      {value}
    </div>
    {sub && <div style={{ fontSize: 12, color: 'var(--text-faint)' }}>{sub}</div>}
    {children}
  </div>
);


// ── Trustpilot star display ──────────────────────────────────────────────────
const TrustpilotStars = ({ score }) => {
  const starPath = "m12 3 2.6 5.5 6 .9-4.3 4.2 1 6-5.3-2.8-5.3 2.8 1-6L3.4 9.4l6-.9z";
  return (
    <div style={{ display: 'flex', gap: 3 }}>
      {Array.from({ length: 5 }, (_, i) => {
        const full  = i < Math.floor(score);
        const half  = !full && i === Math.floor(score) && (score % 1) >= 0.25;
        return (
          <svg key={i} width="16" height="16" viewBox="0 0 24 24"
               fill={full || half ? '#00B67A' : 'none'}
               stroke={full || half ? '#00B67A' : 'var(--border)'}
               strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"
               opacity={half ? 0.55 : 1}>
            <path d={starPath} fill={full ? '#00B67A' : half ? '#00B67A' : 'none'}/>
          </svg>
        );
      })}
    </div>
  );
};

// ── Mini ad card for the Top 3 ads section ───────────────────────────────────
const MiniAdCard = ({ ad }) => (
  <div style={{
    flex: 1, minWidth: 0, borderRadius: 10, overflow: 'hidden',
    border: '1px solid var(--border)',
    background: 'var(--bg-surface)',
  }}>
    <div style={{
      height: 96, background: ad.thumb, position: 'relative',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      {ad.type === 'Video' && (
        <div style={{
          width: 30, height: 30, borderRadius: 999,
          background: 'rgba(0,0,0,0.48)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
        }}>
          <Icon name="play" size={14}/>
        </div>
      )}
      <span style={{
        position: 'absolute', top: 6, left: 6,
        background: 'rgba(0,0,0,0.52)', color: '#fff',
        fontSize: 10, fontWeight: 600, padding: '2px 5px', borderRadius: 4,
      }}>
        {ad.daysActive}d
      </span>
    </div>
    <div style={{ padding: '8px 10px' }}>
      <div style={{
        fontSize: 11, fontWeight: 600, color: 'var(--text)',
        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
      }}>
        {ad.headline}
      </div>
      <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 2 }}>
        {fmtBrandNum(ad.reach)} reach · €{fmtBrandNum(ad.estSpend)}
      </div>
    </div>
  </div>
);

// ── Customize popover button ─────────────────────────────────────────────────
const BrandDetailCustomizeBtn = ({ sections, onChange }) => {
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ position: 'relative' }}>
      <button className="btn btn-stroke btn-sm" onClick={() => setOpen(v => !v)}>
        <Icon name="settings" size={14}/> Customize
      </button>
      {open && (
        <CardCustomizeMenu
          fields={sections}
          options={BRAND_DETAIL_SECTION_OPTIONS}
          onChange={onChange}
          onClose={() => setOpen(false)}
          anchor="right"
        />
      )}
    </div>
  );
};

// ── Main component ────────────────────────────────────────────────────────────
const BrandDetailV3 = ({ brand, onBack }) => {
  const [sections, setSections] = React.useState(BRAND_DETAIL_SECTIONS_DEFAULT);
  const s = sections;

  const brandAds = (ADS_V3 || []).filter(a => a.brandId === brand.id).slice(0, 3);

  const visitorMonths = genMonthLabels();

  const row1Visible = s.activeAds || s.fbPages || s.avgFbLikes || s.trustpilot;
  const row2Visible = s.sales || s.estSpend;
  const row3Visible = s.visitors || s.topCountry;
  const row4Visible = s.topProducts || s.topAds;

  return (
    <>
      <PageHeader
        icon="building"
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <button
              onClick={onBack}
              className="btn btn-ghost btn-icon"
              style={{ width: 28, height: 28, flexShrink: 0 }}
              aria-label="Back to brands"
            >
              <Icon name="chevron-left" size={16}/>
            </button>
            <BrandChip name={brand.name} size={34} square/>
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 16, fontWeight: 600 }}>
                {brand.name}
                {brand.verified && <Icon name="check-circle" size={14} style={{ color: 'var(--accent)' }}/>}
                <Icon name={`flag-${brand.country}`} size={14}/>
              </div>
              <div style={{ fontSize: 12, color: 'var(--text-faint)', fontWeight: 400 }}>{brand.handle}</div>
            </div>
          </div>
        }
        subtitle={null}
        right={<BrandDetailCustomizeBtn sections={sections} onChange={setSections}/>}
      />

      <div style={{ padding: '16px 24px 32px', flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 12 }} className="scroll">

        {/* ── Row 1: 4 stat cards ─────────────────────────────────────── */}
        {row1Visible && (
          <div style={{ display: 'flex', gap: 12 }}>
            {s.activeAds && (
              <StatCardBD icon="sparkles" label="Active ads" value={brand.active}
                sub={`of ${brand.total.toLocaleString()} total`}/>
            )}
            {s.fbPages && (
              <StatCardBD icon="globe" label="FB Pages" value={brand.fbPages}
                sub="pages tracked"/>
            )}
            {s.avgFbLikes && (
              <StatCardBD icon="heart" label="Avg. FB likes" value={fmtBrandNum(brand.avgFbLikes)}
                sub="per page"/>
            )}
            {s.trustpilot && (
              <StatCardBD icon="star" label="Trustpilot" value={brand.trustpilot.score.toFixed(1)}
                sub={`${fmtBrandNum(brand.trustpilot.total)} reviews`}>
                <TrustpilotStars score={brand.trustpilot.score}/>
              </StatCardBD>
            )}
          </div>
        )}

        {/* ── Row 2: Sales chart + Est. spend ─────────────────────────── */}
        {row2Visible && (
          <div style={{ display: 'flex', gap: 12 }}>
            {s.sales && (
              <div className="card" style={{ flex: 2, minWidth: 0, padding: '16px 18px', display: 'flex', flexDirection: 'column', gap: 8 }}>
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                      Total sales
                    </div>
                    <div style={{ fontSize: 28, fontWeight: 700, fontFamily: 'var(--font-mono)', color: 'var(--text)', lineHeight: 1.1, marginTop: 6 }}>
                      €{fmtBrandNum(brand.salesLast30d)}
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 3 }}>last 30 days</div>
                  </div>
                  <span className="badge badge-green">
                    <span style={{ width: 6, height: 6, borderRadius: 999, background: 'currentColor' }}/>
                    Live
                  </span>
                </div>
                <div style={{ marginTop: 8 }}>
                  <MiniAreaChart
                    data={genDailyData(brand.spend, brand.salesLast30d / 30, 30)}
                    labels={DAY_LABELS_30}
                    height={52}
                    formatY={(v) => `€${fmtBrandNum(Math.round(v))}`}
                  />
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--text-faint)' }}>
                  <span>30 days ago</span>
                  <span>Today</span>
                </div>
              </div>
            )}
            {s.estSpend && (
              <div className="card" style={{ flex: 1, minWidth: 0, padding: '16px 18px', display: 'flex', flexDirection: 'column', gap: 6 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                  Est. Ad Spend
                </div>
                <div style={{ fontSize: 28, fontWeight: 700, fontFamily: 'var(--font-mono)', color: 'var(--text)', lineHeight: 1.1, marginTop: 6 }}>
                  €{fmtBrandNum(brand.spend)}
                </div>
                <div style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 3 }}>last 30 days</div>
                <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {[
                    { label: 'CTR',        value: `${brand.ctr}%` },
                    { label: 'CPM',        value: `€${brand.cpm}` },
                    { label: 'Daily est.', value: `€${Math.round(brand.spend / 30).toLocaleString()}` },
                  ].map(({ label, value }) => (
                    <div key={label} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span style={{ fontSize: 12, color: 'var(--text-faint)' }}>{label}</span>
                      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 500, color: 'var(--text)' }}>{value}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {/* ── Row 3: Visitors chart + Top country ─────────────────────── */}
        {row3Visible && (
          <div style={{ display: 'flex', gap: 12 }}>
            {s.visitors && (
              <div className="card" style={{ flex: 2, minWidth: 0, padding: '16px 18px', display: 'flex', flexDirection: 'column', gap: 8 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                      Visitors
                    </div>
                    <div style={{ fontSize: 24, fontWeight: 700, fontFamily: 'var(--font-mono)', color: 'var(--text)', lineHeight: 1.1, marginTop: 6 }}>
                      {fmtBrandNum(brand.visitorsLast6m.reduce((a, b) => a + b, 0))}
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 3 }}>last 6 months</div>
                  </div>
                  {(() => {
                    const last  = brand.visitorsLast6m[brand.visitorsLast6m.length - 1];
                    const prev  = brand.visitorsLast6m[brand.visitorsLast6m.length - 2];
                    const delta = prev > 0 ? Math.round(((last - prev) / prev) * 100) : 0;
                    const up    = delta >= 0;
                    return (
                      <span style={{
                        fontSize: 12, fontWeight: 600, padding: '3px 8px', borderRadius: 6,
                        background: up ? 'var(--success-soft)' : 'var(--danger-soft)',
                        color: up ? 'var(--success)' : 'var(--danger)',
                        display: 'inline-flex', alignItems: 'center', gap: 3,
                      }}>
                        <Icon name={up ? 'trend-up' : 'trend-down'} size={12}/>
                        {up ? '+' : ''}{delta}%
                      </span>
                    );
                  })()}
                </div>
                <div style={{ marginTop: 8 }}>
                  <MiniAreaChart
                    data={brand.visitorsLast6m}
                    labels={visitorMonths}
                    height={64}
                    formatY={(v) => fmtBrandNum(Math.round(v))}
                  />
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--text-faint)', marginTop: 2 }}>
                  {visitorMonths.map(m => <span key={m}>{m}</span>)}
                </div>
              </div>
            )}
            {s.topCountry && (
              <div className="card" style={{ flex: 1, minWidth: 0, padding: '16px 18px', display: 'flex', flexDirection: 'column', gap: 12 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                  Top Country
                </div>
                {(brand.topCountries || []).map(({ c, pct }, i) => {
                  const countryName = (COUNTRIES || []).find(cc => cc.c === c)?.name || c.toUpperCase();
                  return (
                    <div key={c}>
                      {i === 0 && (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                          <Icon name={`flag-${c}`} size={24}/>
                          <div>
                            <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--text)' }}>{countryName}</div>
                            <div style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 1 }}>{pct}% of traffic</div>
                          </div>
                        </div>
                      )}
                      <div style={{ height: 6, borderRadius: 999, background: 'var(--bg-soft)', overflow: 'hidden', marginBottom: 4 }}>
                        <div style={{ width: `${pct}%`, height: '100%', background: i === 0 ? 'var(--accent)' : 'var(--text-faint)', borderRadius: 999, transition: 'width .4s', opacity: i === 0 ? 1 : 0.5 }}/>
                      </div>
                      {i > 0 && (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                          <Icon name={`flag-${c}`} size={14}/>
                          <span style={{ fontSize: 12, color: 'var(--text-2)', flex: 1 }}>{countryName}</span>
                          <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--text-faint)' }}>{pct}%</span>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        )}

        {/* ── Row 4: Top products + Top ads ───────────────────────────── */}
        {row4Visible && (
          <div style={{ display: 'flex', gap: 12 }}>
            {s.topProducts && (
              <div className="card" style={{ flex: 1, minWidth: 0, padding: '16px 18px' }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 4 }}>
                  Top Products
                </div>
                {(brand.products || []).map((p, i) => (
                  <div key={p.name} style={{
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '11px 0',
                    borderBottom: i < (brand.products.length - 1) ? '1px solid var(--border-soft)' : 'none',
                  }}>
                    <div style={{
                      width: 26, height: 26, borderRadius: 7,
                      background: 'var(--bg-soft)', flexShrink: 0,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 700,
                      color: 'var(--text-faint)',
                    }}>
                      {i + 1}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {p.name}
                      </div>
                      <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 1 }}>
                        {p.sales.toLocaleString()} sold
                      </div>
                    </div>
                    <div style={{ textAlign: 'right', flexShrink: 0 }}>
                      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>
                        €{fmtBrandNum(p.revenue)}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
            {s.topAds && (
              <div className="card" style={{ flex: 1, minWidth: 0, padding: '16px 18px' }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 12 }}>
                  Top Ads
                </div>
                {brandAds.length > 0 ? (
                  <div style={{ display: 'flex', gap: 8 }}>
                    {brandAds.map(ad => <MiniAdCard key={ad.id} ad={ad}/>)}
                  </div>
                ) : (
                  <div style={{ color: 'var(--text-faint)', fontSize: 13, textAlign: 'center', padding: '24px 0' }}>
                    No ads found for this brand.
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </div>
    </>
  );
};

Object.assign(window, { BrandDetailV3, BRAND_DETAIL_SECTIONS_DEFAULT, BRAND_DETAIL_SECTION_OPTIONS });
