// Scene — Customer picker (hero moment).
// This is THE screen Matt demos to the C-suite. Every pixel earns its spot.

function GMCustomerPicker({ onPick }) {
  const partner = window.GM_PARTNER;
  const customers = window.GM_CUSTOMERS;

  // Rolled-up partner-level stats — the "you're managing $X across N customers" flex.
  const totals = React.useMemo(() => customers.reduce((a, c) => ({
    cardholders: a.cardholders + c.cardholders,
    decisions:   a.decisions   + c.decisions,
    ai24h:       a.ai24h       + c.ai_handled_24h,
    sites:       a.sites       + c.sites.length,
  }), { cardholders: 0, decisions: 0, ai24h: 0, sites: 0 }), [customers]);

  const goToRealPartnerPortal = () => { window.location.href = '/partner-portal'; };
  const [timeOfDay] = React.useState(() => {
    const h = new Date().getHours();
    if (h < 5)  return 'evening';
    if (h < 12) return 'morning';
    if (h < 17) return 'afternoon';
    return 'evening';
  });

  return (
    <div className="cpk scene">
      {/* Cinematic Mesh backdrop — same treatment as the handoff scene
          (giant breathing shield, sheen, shimmer, grain, warm stripe).
          Continuity across the auth-to-workspace arc. */}
      <span className="cpk-shield" aria-hidden="true"/>
      <span className="cpk-shield-sheen" aria-hidden="true"/>
      <span className="cpk-shield-shine" aria-hidden="true"/>
      <span className="cpk-grain-v2" aria-hidden="true"/>
      <span className="cpk-stripe" aria-hidden="true"/>

      {/* Top bar — quiet, compact, not competing with the hero */}
      <header className="cpk-top">
        <div className="cpk-top-left">
          <GMI.shield style={{ width: 20, height: 22, color: 'var(--text-primary)' }}/>
          <span className="cpk-top-brand">Guardian Mesh</span>
          <span className="cpk-top-chip">
            <span className="dot" style={{ background: 'var(--signal-good)' }}/>
            <span className="mono">SIGNED IN · {partner.name.toUpperCase()}</span>
          </span>
        </div>
        <button className="cpk-return" onClick={goToRealPartnerPortal}>
          <GMI.arrowLeft style={{ width: 13, height: 13 }}/>
          Return to Guardian Mesh Partner Portal
        </button>
      </header>

      <main className="cpk-main">
        {/* Hero */}
        <div className="cpk-hero">
          <div className="cpk-hero-eyebrow">
            <span className="mono">WORKSPACE SELECT</span>
            <span className="cpk-hero-dot"/>
            <span className="mono">{customers.length} CUSTOMERS</span>
          </div>
          <h1 className="cpk-hero-title">
            Good {timeOfDay}, <span className="cpk-hero-name">{partner.user.name.split(' ')[0]}</span>.
            <br/>
            <span className="cpk-hero-subtitle">Choose a customer to enter.</span>
          </h1>
          <p className="cpk-hero-sub">
            Each workspace has its own policies, branding, and Guardian&nbsp;AI context.
            You'll sign in once — Guardian takes you the rest of the way.
          </p>

          {/* Rolled-up stats bar */}
          <div className="cpk-totals">
            <div className="cpk-total">
              <div className="cpk-total-val">{totals.cardholders.toLocaleString()}</div>
              <div className="cpk-total-lbl mono">CARDHOLDERS</div>
            </div>
            <span className="cpk-total-sep"/>
            <div className="cpk-total">
              <div className="cpk-total-val">{totals.ai24h}</div>
              <div className="cpk-total-lbl mono">AI ACTIONS · 24H</div>
            </div>
            <span className="cpk-total-sep"/>
            <div className="cpk-total">
              <div className="cpk-total-val cpk-total-accent">{totals.decisions}</div>
              <div className="cpk-total-lbl mono">NEED YOUR DECISION</div>
            </div>
            <span className="cpk-total-sep"/>
            <div className="cpk-total">
              <div className="cpk-total-val">{totals.sites}</div>
              <div className="cpk-total-lbl mono">SITES</div>
            </div>
          </div>
        </div>

        {/* Customer grid */}
        <div className="cpk-grid">
          {customers.map((c, i) => (
            <GMCustomerTile
              key={c.id}
              c={c}
              onPick={() => onPick(c)}
              index={i}
            />
          ))}
        </div>

        <div className="cpk-foot">
          <span className="mono">Need another workspace?</span>
          <a href="#" onClick={e => e.preventDefault()} className="cpk-foot-link">
            Contact your Alert Enterprise account team to add a customer →
          </a>
        </div>
      </main>
    </div>
  );
}

// Tile — cursor-aware spotlight, staggered fade-in, accent-wash on hover.
function GMCustomerTile({ c, onPick, index }) {
  const ref = React.useRef(null);
  const isProv = c.status === 'provisioning';

  // Cursor-follow spotlight — updates CSS vars on mousemove.
  const onMove = (e) => {
    const el = ref.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const x = ((e.clientX - r.left) / r.width) * 100;
    const y = ((e.clientY - r.top) / r.height) * 100;
    el.style.setProperty('--cursor-x', `${x}%`);
    el.style.setProperty('--cursor-y', `${y}%`);
  };

  return (
    <button
      ref={ref}
      className={`cpk-tile ${isProv ? 'is-prov' : ''}`}
      onClick={onPick}
      onMouseMove={onMove}
      style={{
        '--tile-accent':      c.accent,
        '--tile-accent-soft': c.accentSoft,
        animationDelay: `${index * 90}ms`,
      }}
    >
      {/* Accent glow that tracks the cursor */}
      <span className="cpk-tile-spotlight" aria-hidden="true"/>
      {/* Permanent subtle accent wash in the top-right */}
      <span className="cpk-tile-corner-glow" aria-hidden="true"/>

      <div className="cpk-tile-head">
        <div className="cpk-tile-logo" style={{ background: c.logoBg, color: c.logoFg }}>
          {/* Gradient sheen layer for depth — subtle top-left light */}
          <span className="cpk-tile-logo-sheen" aria-hidden="true"/>
          {/* Translucent orb in the bottom-right for balance */}
          <span className="cpk-tile-logo-orb" aria-hidden="true"/>
          {/* Primary mark — SVG if available, letter fallback otherwise */}
          <span className="cpk-tile-logo-mark">
            {c.logoSvg && GMI[c.logoSvg]
              ? GMI[c.logoSvg]({ width: 30, height: 30 })
              : <span style={{ fontSize: 24, fontWeight: 800, letterSpacing: '-0.03em' }}>{c.logoMark}</span>
            }
          </span>
        </div>
        <div className="cpk-tile-head-right">
          {isProv
            ? <span className="cpk-chip cpk-chip-prov">● Provisioning</span>
            : (c.decisions > 0
                ? <span className="cpk-chip cpk-chip-ai">● {c.decisions} need{c.decisions === 1 ? 's' : ''} you</span>
                : <span className="cpk-chip cpk-chip-ok">● All clear</span>
              )
          }
        </div>
      </div>

      <div className="cpk-tile-id">
        <div className="cpk-tile-name">{c.name}</div>
        <div className="cpk-tile-tagline mono">{c.tagline || `${c.industry} · ${c.region}`}</div>
        <div className="cpk-tile-meta">
          <span className="mono">{c.industry}</span>
          <span className="cpk-tile-meta-dot"/>
          <span className="mono">{c.region}</span>
        </div>
      </div>

      {/* Stat strip */}
      <div className="cpk-tile-stats">
        <div className="cpk-tile-stat">
          <div className="cpk-tile-stat-val">{c.cardholders.toLocaleString()}</div>
          <div className="cpk-tile-stat-lbl mono">CARDHOLDERS</div>
        </div>
        <div className="cpk-tile-stat">
          <div className="cpk-tile-stat-val">{c.ai_handled_24h}</div>
          <div className="cpk-tile-stat-lbl mono">AI · 24H</div>
        </div>
        <div className="cpk-tile-stat">
          <div className="cpk-tile-stat-val">{c.sites.length}</div>
          <div className="cpk-tile-stat-lbl mono">SITES</div>
        </div>
      </div>

      {/* Sites strip — small bit of context so each tile feels unique */}
      <div className="cpk-tile-sites">
        {c.sites.slice(0, 3).map((s, i) => (
          <span className="cpk-tile-site mono" key={i}>{s}</span>
        ))}
        {c.sites.length > 3 && <span className="cpk-tile-site cpk-tile-site-more mono">+{c.sites.length - 3}</span>}
      </div>

      {/* CTA row */}
      <div className="cpk-tile-foot">
        <span className="mono">Deployed {c.deployed}</span>
        <span className="cpk-tile-cta">
          Open Guardian Portal
          <span className="cpk-tile-cta-arrow"><GMI.arrowRight style={{ width: 13, height: 13 }}/></span>
        </span>
      </div>

      {/* Full-width accent bar — grows on hover */}
      <span className="cpk-tile-accent-bar" aria-hidden="true"/>
    </button>
  );
}

window.GMCustomerPicker = GMCustomerPicker;
