// Segment Profile Snapshot - deep dive into a single segment
// no top-level destructured hooks

function ProfileBackBtn({ onBack }) {
  return (
    <button className="profile-back" onClick={onBack}>
      <span style={{ fontSize: 14 }}>←</span> Back to overview
    </button>
  );
}

function HBar({ label, value, max, fmtFn, color }) {
  const pct = max > 0 ? (value / max) * 100 : 0;
  return (
    <div className="hbar">
      <div className="hbar-label">{label}</div>
      <div className="hbar-track">
        <div className="hbar-fill" style={{ width: pct+'%', background: color || 'var(--navy)' }} />
      </div>
      <div className="hbar-val">{fmtFn(value)}</div>
    </div>
  );
}

function VisitDistChart({ buckets, dist }) {
  const max = Math.max(...dist, 0.01);
  return (
    <div>
      <div className="vbar-wrap">
        {dist.map((v, i) => (
          <div className="vbar-col" key={i}>
            <div style={{ fontSize: 10.5, color: 'var(--ink-3)', fontFamily: 'JetBrains Mono', height: 14 }}>
              {v > 0.005 ? (v*100).toFixed(0)+'%' : ''}
            </div>
            <div className="vbar-bar" style={{ height: `${(v/max)*100}%`, background: i === dist.indexOf(max) ? 'var(--red)' : 'var(--navy)' }} />
            <div className="vbar-x">{buckets[i]}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function MonthlyChart({ values, months }) {
  const max = Math.max(...values, 1);
  return (
    <div className="vbar-wrap" style={{ height: 110 }}>
      {values.map((v, i) => (
        <div className="vbar-col" key={i}>
          <div className="vbar-bar" style={{ height: `${(v/max)*100}%`, background: 'var(--navy)' }} />
          <div className="vbar-x" style={{ fontSize: 10 }}>{months[i]}</div>
        </div>
      ))}
    </div>
  );
}

function DowChart({ dow }) {
  const days = [
    { k: 'mon', l: 'Mon', wk: true },
    { k: 'tue', l: 'Tue', wk: true },
    { k: 'wed', l: 'Wed', wk: true },
    { k: 'thu', l: 'Thu', wk: true },
    { k: 'fri', l: 'Fri', wk: true },
    { k: 'sat', l: 'Sat', wk: false },
    { k: 'sun', l: 'Sun', wk: false },
  ];
  const max = Math.max(...days.map(d => dow[d.k]), 1);
  return (
    <div className="vbar-wrap" style={{ height: 100 }}>
      {days.map((d) => (
        <div className="vbar-col" key={d.k}>
          <div className="vbar-bar" style={{
            height: `${(dow[d.k]/max)*100}%`,
            background: d.wk ? 'var(--navy)' : 'var(--red)',
          }} />
          <div className="vbar-x">{d.l}</div>
        </div>
      ))}
    </div>
  );
}

function StackBar({ items, total }) {
  return (
    <div style={{ display: 'flex', height: 22, borderRadius: 6, overflow: 'hidden', background: 'var(--line-2)' }}>
      {items.map((it, i) => (
        <div key={i} title={`${it.label}: ${fmt.pct(it.value/total, 1)}`}
          style={{
            width: `${(it.value/total)*100}%`,
            background: it.color,
          }} />
      ))}
    </div>
  );
}

function SegmentProfileView({ segment, venue, onBack }) {
  const s = segment;

  // Game category breakdown
  const gameCats = [
    { key: 'ticketGame', label: 'Ticket Game', color: '#1a2a5e' },
    { key: 'prize', label: 'Prize Game', color: '#e63329' },
    { key: 'stdVideo', label: 'Standard Video', color: '#5a76c7' },
    { key: 'attractions', label: 'Attractions', color: '#f5d616' },
    { key: 'stdNonVideo', label: 'Std Non-Video', color: '#8aa0d6' },
    { key: 'nonGame', label: 'Non Game', color: '#9aa3bf' },
    { key: 'ticketEater', label: 'Ticket Eater', color: '#3a4566' },
  ];
  const gcMax = Math.max(...gameCats.map(c => s.gameByCat[c.key]));

  // Redemption categories
  const redeemCats = ["Snacks","Toys & Hobbies","Homeware","Stationery","Collectables","Accessories","Plush Toys","Electronic","Special Prize"];
  const redeemColors = ['#1a2a5e','#e63329','#f5d616','#5a76c7','#8aa0d6','#b58e00','#2e4a9f','#9aa3bf','#cdd3e3'];

  // Load amount bands
  const loadBands = ["<100K","100-200K","200-300K","300-500K","500K-1M","1M-2M","2M+"];

  return (
    <div>
      {/* Hero */}
      <div className="profile-hero">
        <ProfileBackBtn onBack={onBack} />
        <h1 className="profile-name">
          <span style={{ width: 8, height: 36, borderRadius: 3, background: SEG_COLORS[s.key] }} />
          {s.key}
          <span className="pill" style={{ background: 'rgba(245,214,22,.18)', color: 'var(--gold)', fontSize: 11, padding: '4px 10px', borderRadius: 999, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', marginLeft: 6 }}>
            {s.tier}
          </span>
        </h1>
        <div className="profile-tag">{s.tagline} · {venue.name} venue snapshot</div>

        <div className="profile-hero-stats">
          <div>
            <div className="phs-label">Guests in segment</div>
            <div className="phs-value">{fmt.int(s.userCount)}</div>
            <div style={{ fontSize: 11, opacity: 0.7, marginTop: 2 }}>{fmt.pct(s.pctUsers,1)} of base</div>
          </div>
          <div>
            <div className="phs-label">Revenue contributed</div>
            <div className="phs-value gold">{fmt.idr(s.revenue)}</div>
            <div style={{ fontSize: 11, opacity: 0.7, marginTop: 2 }}>{fmt.pct(s.revPct,1)} of revenue</div>
          </div>
          <div>
            <div className="phs-label">Avg revenue / guest</div>
            <div className="phs-value">{fmt.idr(s.avgRev)}</div>
            <div style={{ fontSize: 11, opacity: 0.7, marginTop: 2 }}>per guest, lifetime</div>
          </div>
          <div>
            <div className="phs-label">Profit margin</div>
            <div className="phs-value" style={{ color: s.profitPct < 0.1 ? 'var(--red)' : s.profitPct > 0.5 ? '#7be8a3' : 'var(--gold)' }}>
              {fmt.pct(s.profitPct,1)}
            </div>
            <div style={{ fontSize: 11, opacity: 0.7, marginTop: 2 }}>of segment revenue</div>
          </div>
        </div>
      </div>

      {/* Section: behaviour signals */}
      <div className="section-head" style={{ marginTop: 28 }}>
        <h2>Engagement signals</h2>
        <div className="meta">How frequently and how long they engage</div>
      </div>

      <div className="grid grid-4">
        <KPI label="Avg visits / guest" value={s.visitAvg.toFixed(1)} foot={`Median ${s.visitMed}`} />
        <KPI label="Avg dwell time" value={s.dwellAvg} subUnit="min" foot={`Median ${s.dwellMed} min`} />
        <KPI label="Visit interval" value={s.intervalAvg ?? '—'} subUnit={s.intervalAvg ? 'days' : ''} foot={s.intervalMed ? `Median ${s.intervalMed} days` : 'Single visit'} />
        <KPI label="Game plays" value={fmt.num(s.gameTotal)} foot={`Avg ${s.gameAvg} / guest`} />
      </div>

      {/* Visits + day-of-week + monthly */}
      <div className="grid grid-12" style={{ marginTop: 16 }}>
        <div className="card col-4">
          <div className="card-head">
            <div>
              <div className="card-title">Visit frequency</div>
              <div className="card-sub">Distribution by # of visits</div>
            </div>
          </div>
          <VisitDistChart buckets={["1","2","3","4","5-10","10+"]} dist={s.visitDist} />
        </div>

        <div className="card col-4">
          <div className="card-head">
            <div>
              <div className="card-title">Day of week</div>
              <div className="card-sub">{fmt.pct(s.weekdayPct,0)} weekday · {fmt.pct(s.weekendPct,0)} weekend</div>
            </div>
          </div>
          <DowChart dow={s.dow} />
        </div>

        <div className="card col-4">
          <div className="card-head">
            <div>
              <div className="card-title">Monthly visits</div>
              <div className="card-sub">{fmt.int(s.totalVisits)} total this period</div>
            </div>
          </div>
          <MonthlyChart values={Array.isArray(s.monthly) ? s.monthly : (s.monthly?.months || [])} months={["J","F","M","A","M","J","J","A","S","O","N","D"]} />
        </div>
      </div>

      {/* Game preference */}
      <div className="section-head">
        <h2>Game preferences</h2>
        <div className="meta">Where this segment spends their plays</div>
      </div>

      <div className="grid grid-12">
        <div className="card col-7">
          <div className="card-head">
            <div>
              <div className="card-title">Plays by category</div>
              <div className="card-sub">Total {fmt.num(s.gameTotal)} plays</div>
            </div>
          </div>
          <div>
            {gameCats.map(c => (
              <HBar
                key={c.key}
                label={c.label}
                value={s.gameByCat[c.key]}
                max={gcMax}
                color={c.color}
                fmtFn={(v) => fmt.num(v)}
              />
            ))}
          </div>
        </div>

        <div className="card col-5">
          <div className="card-head">
            <div>
              <div className="card-title">Top 5 games played</div>
              <div className="card-sub">By total plays</div>
            </div>
          </div>
          <table className="t">
            <thead>
              <tr>
                <th>#</th>
                <th>Game</th>
                <th style={{ textAlign: 'right' }}>Plays</th>
                <th style={{ textAlign: 'right' }}>Players</th>
              </tr>
            </thead>
            <tbody>
              {s.topGames.map((g) => (
                <tr key={g.rank}>
                  <td className="rank-cell">{g.rank}</td>
                  <td>
                    <div className="strong">{g.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>
                      <span className="pill">{g.cat}</span> &nbsp;{g.cls}
                    </div>
                  </td>
                  <td className="num">{fmt.num(g.plays)}</td>
                  <td className="num">{fmt.num(g.players)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Tickets / spend */}
      <div className="section-head">
        <h2>Tickets & spend pattern</h2>
        <div className="meta">Redemption behaviour and load amounts</div>
      </div>

      <div className="grid grid-12">
        <div className="card col-4">
          <div className="card-head">
            <div>
              <div className="card-title">Ticket flow</div>
              <div className="card-sub">Won vs redeemed</div>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 6 }}>
            <div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 4 }}>Tickets won</div>
              <div className="kpi-value" style={{ fontSize: 22 }}>{fmt.num(s.tixWon)}</div>
            </div>
            <div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 4 }}>Tickets redeemed</div>
              <div className="kpi-value" style={{ fontSize: 22 }}>{fmt.num(s.tixRed)}</div>
            </div>
            <div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 4 }}>Redemption rate</div>
              <div className="kpi-value" style={{ fontSize: 22, color: 'var(--red)' }}>
                {s.tixWon > 0 ? fmt.pct(s.tixRed/s.tixWon, 1) : '—'}
              </div>
            </div>

          </div>
        </div>

        <div className="card col-4">
          <div className="card-head">
            <div>
              <div className="card-title">Load amount distribution</div>
              <div className="card-sub">Where their loaded value sits</div>
            </div>
          </div>
          <div>
            {s.loadDist.map((v, i) => (
              <HBar
                key={i}
                label={loadBands[i]}
                value={v}
                max={Math.max(...s.loadDist, 0.01)}
                color={SEG_COLORS[s.key]}
                fmtFn={(x) => (x*100).toFixed(1)+'%'}
              />
            ))}
          </div>
        </div>

        <div className="card col-4">
          <div className="card-head">
            <div>
              <div className="card-title">Redemption preference</div>
              <div className="card-sub">Categories chosen at redemption</div>
            </div>
          </div>
          <div style={{ marginBottom: 10 }}>
            <StackBar
              items={s.redeemDist.map((v, i) => ({ label: redeemCats[i], value: v, color: redeemColors[i] }))}
              total={s.redeemDist.reduce((a,b) => a+b, 0)}
            />
          </div>
          <div className="legend">
            {s.redeemDist
              .map((v, i) => ({ v, i }))
              .filter(x => x.v > 0.005)
              .sort((a,b) => b.v - a.v)
              .slice(0, 6)
              .map(({ v, i }) => (
                <div className="legend-row" key={i}>
                  <div className="legend-swatch" style={{ background: redeemColors[i] }} />
                  <div className="legend-label">{redeemCats[i]}</div>
                  <div className="legend-val">{fmt.pct(v, 1)}</div>
                </div>
              ))}
          </div>
        </div>
      </div>

      {/* Top trophies */}
      <div className="section-head">
        <h2>Top redemption items</h2>
        <div className="meta">Most valuable items claimed by this segment</div>
      </div>

      <div className="card" style={{ padding: 0 }}>
        <table className="t" style={{ padding: '4px 18px' }}>
          <thead>
            <tr>
              <th style={{ paddingLeft: 18 }}>#</th>
              <th>Item</th>
              <th style={{ textAlign: 'right' }}>Avg ticket cost</th>
              <th style={{ textAlign: 'right' }}>Quantity taken</th>
              <th style={{ textAlign: 'right', paddingRight: 18 }}>Unique guests</th>
            </tr>
          </thead>
          <tbody>
            {s.topTrophies.map((t) => (
              <tr key={t.rank}>
                <td className="rank-cell" style={{ paddingLeft: 18 }}>{t.rank}</td>
                <td className="strong">{t.name}</td>
                <td className="num">{fmt.int(t.cost)} tix</td>
                <td className="num">{fmt.int(t.qty)}</td>
                <td className="num" style={{ paddingRight: 18 }}>{fmt.int(t.users)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.SegmentProfileView = SegmentProfileView;
