// hero-carousel.jsx — split hero showcase for Intelligence and Asset Ops.
// The snapshots share ONE chrome (DashShell) so they're visually uniform.
// Must load AFTER wf.jsx, dashboard.jsx, hf.jsx, hf-data.jsx.

// ── product theming ───────────────────────────────────────────────────────────
const PROD = {
  intelligence: { label: 'Intelligence', arm: '#2351d4', soft: '#ebefff', bd: '#bfccf7' },
  asset:        { label: 'Asset Ops',    arm: '#0d7c73', soft: '#edfaf8', bd: '#9addd7' },
};

// ── K-product logo (real provided wordmark images) ──────────────────────────────
const LOGO_SRC = {
  intelligence: 'logos/intelligence.png',
  asset: 'logos/asset.png',
};
function KProductLogo({ product, height = 19 }) {
  const src = LOGO_SRC[product] || LOGO_SRC.intelligence;
  return <img src={src} alt={`Kyndrid ${PROD[product].label}`} style={{ height, width: 'auto', display: 'block' }} />;
}
// standalone K mark
function KMark({ size = 22 }) {
  return <img src="logos/mark.png" alt="Kyndrid" style={{ height: size, width: 'auto', display: 'block' }} />;
}

// ── mini charts ─────────────────────────────────────────────────────────────────
function CBars({ data, h = 22, accent, base = '#e2e8f2' }) {
  const max = Math.max(...data);
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 2.5, height: h }}>
      {data.map((v, i) => (
        <div key={i} style={{ flex: 1, height: `${(v / max) * 100}%`, borderRadius: 1.5, background: i === data.length - 1 ? accent : base }} />
      ))}
    </div>
  );
}
function CArea({ pts, h = 96, w = 320, accent, soft }) {
  const max = Math.max(...pts), min = Math.min(...pts);
  const norm = (v) => h - ((v - min) / (max - min || 1)) * (h - 16) - 8;
  const step = w / (pts.length - 1);
  const d = pts.map((v, i) => `${i === 0 ? 'M' : 'L'}${(i * step).toFixed(1)},${norm(v).toFixed(1)}`).join(' ');
  return (
    <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <path d={`${d} L${w},${h} L0,${h} Z`} fill={soft} opacity="0.6" />
      <path d={d} fill="none" stroke={accent} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// ── shared dashboard shell — guarantees uniform look across all three ──────────
function DashShell({ w = 600, product, account, breadcrumb, title, subtitle, sidebar, metrics, children }) {
  const t = PROD[product];
  return (
    <div style={{ width: w, background: '#fff', borderRadius: 16, border: '1px solid #e2e8f2', overflow: 'hidden', fontFamily: HF.font, display: 'flex', flexDirection: 'column' }}>
      {/* topbar */}
      <div style={{ height: 44, borderBottom: '1px solid #e2e8f2', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 14px', background: HF.fill, flex: '0 0 auto' }}>
        <KProductLogo product={product} height={19} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 10.5, fontWeight: 600, color: HF.muted, padding: '3px 9px', border: '1px solid #e2e8f2', borderRadius: 6 }}>{account} ▾</span>
          <span style={{ fontSize: 10, fontWeight: 700, color: t.arm, background: t.soft, border: `1px solid ${t.bd}`, borderRadius: 6, padding: '3px 9px' }}>TODAY</span>
          <span style={{ width: 22, height: 22, borderRadius: 11, background: '#e2e8f2' }} />
        </div>
      </div>
      <div style={{ display: 'flex', flex: 1 }}>
        {/* dark sidebar */}
        <div style={{ width: 108, background: '#07101f', display: 'flex', flexDirection: 'column', padding: '12px 0', flex: '0 0 auto' }}>
          {sidebar.map((sec, si) => (
            <div key={sec.label} style={{ padding: '0 10px 10px', borderBottom: si < sidebar.length - 1 ? '1px solid rgba(255,255,255,.08)' : 'none', marginBottom: si < sidebar.length - 1 ? 8 : 0 }}>
              <div style={{ fontSize: 8.5, fontWeight: 700, color: '#475569', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 5 }}>{sec.label}</div>
              {sec.items.map((it, ii) => {
                const active = si === 0 && ii === 0;
                return (
                  <div key={it} style={{ fontSize: active ? 11 : 10.5, fontWeight: active ? 700 : 500, color: active ? '#fff' : '#64748b', background: active ? t.arm : 'transparent', borderRadius: 6, padding: '5px 9px', marginBottom: 2 }}>{it}</div>
                );
              })}
            </div>
          ))}
        </div>
        {/* main */}
        <div style={{ flex: 1, padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 10, minWidth: 0 }}>
          <div>
            <div style={{ fontSize: 9, fontWeight: 600, color: HF.muted, letterSpacing: '0.05em', textTransform: 'uppercase' }}>{breadcrumb}</div>
            <div style={{ fontSize: 17, fontWeight: 800, color: HF.ink, letterSpacing: '-0.5px', marginTop: 1 }}>{title}</div>
            <div style={{ fontSize: 10.5, color: HF.muted, marginTop: 1 }}>{subtitle}</div>
          </div>
          {/* 5 uniform metric tiles */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5,1fr)', gap: 7 }}>
            {metrics.map((m) => (
              <div key={m.l} style={{ border: `1px solid ${m.al ? '#fcd9a8' : '#e2e8f2'}`, borderRadius: 9, padding: '8px 9px', background: m.al ? '#fffbeb' : '#fff' }}>
                <div style={{ fontSize: 9, fontWeight: 600, color: HF.muted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.l}</div>
                <div style={{ fontSize: 18, fontWeight: 800, color: m.al ? '#d97706' : HF.ink, letterSpacing: '-0.5px', marginTop: 2 }}>{m.v}</div>
                <div style={{ fontSize: 8.5, color: '#94a3b8', marginTop: 2, lineHeight: 1.3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.s}</div>
              </div>
            ))}
          </div>
          {/* product-specific 2-col content */}
          <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 0.9fr', gap: 10, flex: 1 }}>
            {children}
          </div>
        </div>
      </div>
    </div>
  );
}

// small reusable content card
function DCard({ title, badge, badgeTone, children, pad = 11 }) {
  return (
    <div style={{ border: '1px solid #e2e8f2', borderRadius: 11, padding: pad, background: '#fff', display: 'flex', flexDirection: 'column' }}>
      {title && (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
          <span style={{ fontSize: 11, fontWeight: 700, color: HF.ink }}>{title}</span>
          {badge && <span style={{ fontSize: 8.5, fontWeight: 700, color: badgeTone ? badgeTone.arm : HF.muted, background: badgeTone ? badgeTone.soft : 'transparent', border: badgeTone ? `1px solid ${badgeTone.bd}` : 'none', borderRadius: 4, padding: '2px 6px' }}>{badge}</span>}
        </div>
      )}
      {children}
    </div>
  );
}

// ── KYNDRID INTELLIGENCE ────────────────────────────────────────────────────────
function DashIntelligence({ w = 600 }) {
  const t = PROD.intelligence;
  return (
    <DashShell w={w} product="intelligence" account="Riverside Group"
      breadcrumb="INTELLIGENCE / DASHBOARD" title="Dashboard" subtitle="Live trading performance across every site."
      sidebar={[
        { label: 'OVERVIEW', items: ['Dashboard', 'Reports', 'Messages'] },
        { label: 'TRADING', items: ['Sales', 'Inventory', 'Menu', 'Suppliers'] },
        { label: 'OPERATIONS', items: ['Labour', 'People', 'Compliance'] },
      ]}
      metrics={[
        { l: 'Sales today', v: '£8,420', s: '▲ 6.2%' },
        { l: 'Gross margin', v: '64.1%', s: '▲ 1.4%' },
        { l: 'Labour cost', v: '28.6%', s: 'vs 26% plan', al: true },
        { l: 'Covers', v: '612', s: '▲ 4.0%' },
        { l: 'Compliance', v: '92', s: 'of 100' },
      ]}>
      <DCard title="Sales vs demand forecast" badge="7 days" badgeTone={t}>
        <CArea pts={[30, 45, 38, 60, 52, 72, 64, 88]} accent={t.arm} soft={t.soft} h={92} />
        <div style={{ display: 'flex', gap: 14, marginTop: 8 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 9.5, color: HF.muted }}><span style={{ width: 8, height: 3, borderRadius: 2, background: t.arm }} /> Actual sales</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 9.5, color: HF.muted }}><span style={{ width: 8, height: 3, borderRadius: 2, background: '#cbd5e1' }} /> Forecast</span>
        </div>
      </DCard>
      <DCard title="Recommendations" badge="3 new" badgeTone={t}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
          {['Reorder draught lines before Friday', 'Cut Tuesday evening labour by 1 shift', 'Menu item #14 margin slipping — review price'].map((r, i) => (
            <div key={i} style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
              <span style={{ marginTop: 1, color: t.arm, flex: '0 0 auto' }}><svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M3 8h9M9 4l4 4-4 4" /></svg></span>
              <span style={{ fontSize: 11, lineHeight: 1.4, color: '#3d4f68' }}>{r}</span>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 'auto', paddingTop: 10, borderTop: '1px solid #f4f6fb', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ fontSize: 9.5, color: HF.muted }}>Updated 2 min ago</span>
          <span style={{ fontSize: 10, fontWeight: 700, color: t.arm }}>View all →</span>
        </div>
      </DCard>
    </DashShell>
  );
}

// ── ASSET OPS ────────────────────────────────────────────────────────────────────
function DashAssetOps({ w = 600 }) {
  const t = PROD.asset;
  const categories = [
    { n: 'IT Equipment',    pct: 18, count: 21, val: '£35,460', col: '#3b82f6' },
    { n: 'Furniture',       pct: 18, count: 21, val: '£20,320', col: '#8b5cf6' },
    { n: 'Office Equip.',   pct: 13, count: 15, val: '£14,200', col: '#22c55e' },
    { n: 'Electrical',      pct: 23, count: 26, val: '£17,938', col: '#f59e0b' },
    { n: 'Vehicles',        pct: 3,  count: 3,  val: '£34,850', col: '#ef4444' },
    { n: 'Building & Fac.', pct: 13, count: 15, val: '£12,065', col: '#6b7280' },
  ];
  const sites = [
    { n: 'HQ · Croydon', count: 15, pct: 100 },
    { n: 'Bradford Office', count: 10, pct: 67 },
    { n: 'Birmingham Branch', count: 10, pct: 67 },
    { n: 'Leicester Branch', count: 9, pct: 60 },
    { n: 'Glasgow Branch', count: 9, pct: 60 },
  ];
  return (
    <DashShell w={w} product="asset" account="All sites"
      breadcrumb="ASSETOPS / DASHBOARD" title="Dashboard" subtitle="Charity-wide performance, risk and action summary."
      sidebar={[
        { label: 'OVERVIEW', items: ['Dashboard', 'Reports', 'Messages'] },
        { label: 'ASSETS', items: ['Asset Register', 'Purchases', 'Kits', 'Licences'] },
        { label: 'OPERATIONS', items: ['Site Transfers', 'Audits', 'Compliance', 'Maintenance'] },
      ]}
      metrics={[
        { l: 'Total assets', v: '115', s: 'Registered' },
        { l: 'Total sites', v: '26', s: 'All site types' },
        { l: 'Est. value', v: '£148k', s: 'Register value' },
        { l: 'Need action', v: '32', s: '21 condition', al: true },
        { l: 'Audits due', v: '329', s: 'Next 30 days', al: true },
      ]}>
      <DCard title="Assets by category" badge="Live mix" badgeTone={t}>
        <div style={{ fontSize: 8.5, color: HF.muted }}>Register composition</div>
        <div style={{ fontSize: 15, fontWeight: 800, color: HF.ink, letterSpacing: '-0.4px', marginTop: 1 }}>115 assets</div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 1 }}>
          <span style={{ fontSize: 8.5, color: HF.muted }}>Across 26 sites</span>
          <span style={{ fontSize: 8.5, fontWeight: 700, color: HF.ink }}>£148,153 total value</span>
        </div>
        <div style={{ display: 'flex', height: 7, borderRadius: 3, overflow: 'hidden', gap: 1.5, margin: '7px 0' }}>
          {categories.map(c => <div key={c.n} style={{ flex: c.pct, background: c.col }} />)}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 5 }}>
          {categories.map(c => (
            <div key={c.n} style={{ border: '1px solid #e2e8f2', borderRadius: 7, padding: '6px 8px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 9.5, fontWeight: 600, color: '#3d4f68' }}>{c.n}</span>
                <span style={{ fontSize: 9, fontWeight: 700, color: HF.muted }}>{c.pct}%</span>
              </div>
              <div style={{ fontSize: 8.5, color: '#94a3b8', marginTop: 1 }}>{c.val}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 5 }}>
                <span style={{ fontSize: 13, fontWeight: 800, color: HF.ink, lineHeight: 1 }}>{c.count}</span>
                <div style={{ flex: 1, height: 3, borderRadius: 1.5, background: '#e2e8f2', overflow: 'hidden' }}>
                  <div style={{ width: `${Math.min(c.pct * 4, 100)}%`, height: '100%', background: c.col }} />
                </div>
              </div>
            </div>
          ))}
        </div>
      </DCard>
      <DCard title="Assets by site" badge="Top locations">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
          {sites.map(s => (
            <div key={s.n}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 3 }}>
                <span style={{ fontSize: 10.5, fontWeight: 600, color: '#3d4f68' }}>{s.n}</span>
                <span style={{ fontSize: 10, color: HF.muted }}>{s.count}</span>
              </div>
              <div style={{ height: 4, borderRadius: 2, background: '#e2e8f2', overflow: 'hidden' }}>
                <div style={{ width: `${s.pct}%`, height: '100%', background: t.arm, borderRadius: 2 }} />
              </div>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 'auto', paddingTop: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderTop: '1px solid #f4f6fb' }}>
          <div>
            <div style={{ fontSize: 10.5, fontWeight: 700, color: HF.ink }}>Estate health</div>
            <div style={{ fontSize: 9.5, color: HF.muted, marginTop: 1 }}>Across all sites</div>
          </div>
          <span style={{ fontSize: 9.5, fontWeight: 700, color: '#d97706', background: '#fffbeb', border: '1px solid #fcd9a8', borderRadius: 5, padding: '3px 8px', whiteSpace: 'nowrap' }}>16 watch</span>
        </div>
      </DCard>
    </DashShell>
  );
}

// ── HERO AUTO-SWITCHING DASHBOARD ──────────────────────────────────────────────
function HeroCarousel({ w = 600 }) {
  const intervalMs = 6000;
  const stageH = 430;
  const slides = [
    { key: 'intelligence', render: () => <DashIntelligence w={w} /> },
    { key: 'asset', render: () => <DashAssetOps w={w} /> },
  ];
  const [active, setActive] = React.useState(0);
  const [cycle, setCycle] = React.useState(0);
  const [reduceMotion, setReduceMotion] = React.useState(false);

  React.useEffect(() => {
    const media = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)');
    if (!media) return;
    const update = () => setReduceMotion(media.matches);
    update();
    if (media.addEventListener) {
      media.addEventListener('change', update);
      return () => media.removeEventListener('change', update);
    }
    media.addListener(update);
    return () => media.removeListener(update);
  }, []);

  React.useEffect(() => {
    const id = setTimeout(() => {
      setActive((a) => (a + 1) % slides.length);
      setCycle((c) => c + 1);
    }, intervalMs);
    return () => clearTimeout(id);
  }, [active, cycle]);

  const switchSlide = () => {
    setActive((a) => (a + 1) % slides.length);
    setCycle((c) => c + 1);
  };
  const activeTone = PROD[slides[active].key];

  return (
    <div style={{
      width: w, height: stageH, position: 'relative',
      cursor: 'pointer', userSelect: 'none',
    }} onClick={switchSlide} title="Click to switch platform preview">
      <div style={{
        position: 'absolute', inset: 0,
        borderRadius: 18, overflow: 'hidden',
        boxShadow: '0 36px 88px -20px rgba(7,16,31,.30), 0 8px 32px -12px rgba(7,16,31,.12)',
      }}>
        {slides.map((slide, i) => (
          <div key={slide.key} style={{
            position: 'absolute', inset: 0,
            opacity: i === active ? 1 : 0,
            pointerEvents: i === active ? 'auto' : 'none',
            transition: reduceMotion ? 'none' : 'opacity .64s cubic-bezier(.16,1,.3,1)',
          }}>
            {slide.render()}
          </div>
        ))}
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0, height: 2,
          background: 'rgba(226,232,242,.92)', zIndex: 4,
        }}>
          <div
            key={cycle}
            className="k-hero-progress"
            style={{
              width: '100%', height: '100%', transformOrigin: 'left center',
              background: activeTone.arm,
              animation: reduceMotion ? 'none' : `kHeroProgress ${intervalMs}ms linear both`,
              transform: reduceMotion ? 'scaleX(1)' : undefined,
            }}
          />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HeroCarousel, DashIntelligence, DashAssetOps, KProductLogo, KMark, LOGO_SRC, PROD, DashShell, DCard, CBars, CArea });
