// Hero KPI strip — system-grounded metrics only

const fmtMoney = (n) => '$' + (n >= 1e6 ? (n/1e6).toFixed(2) + 'M' : n >= 1e3 ? (n/1e3).toFixed(1) + 'K' : n.toLocaleString());
const fmtMoneyFull = (n) => '$' + Math.round(n).toLocaleString();
const fmtPct = (n) => (n > 0 ? '+' : '') + n.toFixed(1) + '%';
const fmtHrs = (n) => n >= 1000 ? (n/1000).toFixed(1) + 'K hrs' : n.toLocaleString() + ' hrs';

const InfoDot = ({ tip }) => (
  <span className="info-dot" tabIndex={0} aria-label={tip}>
    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 16v-4M12 8h.01"/></svg>
    <span className="info-tip">{tip}</span>
  </span>
);

const KpiTile = ({ icon, iconColor, label, value, sub, delta, deltaPositive, info }) => (
  <div className="kpi-tile">
    <div className="kpi-row">
      <div className="kpi-icon" style={{ color: iconColor, background: iconColor + '22' }}>
        <Icon name={icon} size={14} stroke={2} />
      </div>
      <div className="kpi-label">{label}{info && <InfoDot tip={info}/>}</div>
      {delta !== undefined && (
        <div className={'kpi-delta ' + (deltaPositive ? 'is-up' : 'is-down')}>
          <Icon name={deltaPositive ? 'arrow-up' : 'arrow-down'} size={11} stroke={2.4} />
          {delta}
        </div>
      )}
    </div>
    <div className="kpi-value">{value}</div>
    {sub && <div className="kpi-sub">{sub}</div>}
  </div>
);

const HeroKpiStrip = ({ k, period }) => {
  const periodLabel = ({T:'Today', WTD:'Week to date', MTD:'Month to date', QTD:'Quarter to date', YTD:'Year to date'})[period];
  const net = window.FRANCHISE_DATA.NETWORK;
  return (
    <section className="hero">
      <div className="hero-head">
        <div className="hero-head-left">
          <div className="hero-head-icon"><Icon name="trend" size={18} stroke={2} /></div>
          <div>
            <div className="hero-head-title">Network at a Glance</div>
            <div className="hero-head-sub">{net.totalLocations} locations · {net.franchised} franchised · {net.corporate} corporate · {periodLabel}</div>
          </div>
        </div>
        <div className="hero-head-meta">
          <div className="hero-meta-item"><span className="hero-meta-dot" style={{ background:'#22c55e' }}/><span>6 healthy</span></div>
          <div className="hero-meta-item"><span className="hero-meta-dot" style={{ background:'#f59e0b' }}/><span>2 watch</span></div>
          <div className="hero-meta-item"><span className="hero-meta-dot" style={{ background:'#ef4444' }}/><span>2 risk</span></div>
        </div>
      </div>

      <div className="kpi-grid">
        <KpiTile icon="dollar"   iconColor="#22c55e" label="Net Sales"        value={fmtMoney(k.netSales)} sub={`${fmtMoneyFull(k.productSales)} retail`}
                 info="Total gross sales across all 10 locations for the selected period — services + retail products + tips + gift cards."/>
        <KpiTile icon="scissors" iconColor="#34d399" label="Service Sales"    value={fmtMoney(k.serviceSales)} sub={`${((k.serviceSales/k.netSales)*100).toFixed(0)}% of net sales`}
                 info="Revenue from services only (cuts, shaves, color, etc). Excludes retail product sales."/>
        <KpiTile icon="percent"  iconColor="#fbbf24" label="Utilization"      value={k.utilization.toFixed(1) + '%'} sub={`${fmtHrs(k.bookedHours)} of ${fmtHrs(k.availableHours)}`} delta={k.utilization >= 75 ? 'on target' : (75 - k.utilization).toFixed(1) + '% gap'} deltaPositive={k.utilization >= 75}
                 info="Booked ÷ available chair-hours across the network. Target is 75% — anything lower means empty chairs. The capacity number you actually care about; raw hours are operator-level detail."/>
        <KpiTile icon="dollar"   iconColor="#38bdf8" label="Revenue / Hour"   value={'$' + k.revPerHour.toFixed(2)} sub="Per booked chair-hour"
                 info="Service revenue ÷ booked hours. How much each occupied chair-hour earns. Combine with utilization to see real productivity."/>
        <KpiTile icon="close"    iconColor="#fb7185" label="Cancellation Rate" value={k.cancellationRate.toFixed(1) + '%'} sub="Of booked appointments" delta={k.cancellationRate <= 5 ? 'healthy' : 'high'} deltaPositive={k.cancellationRate <= 5}
                 info="% of appointments cancelled before the visit. Industry benchmark is under 5%."/>
        <KpiTile icon="warn"     iconColor="#f97316" label="No-Show Rate"     value={k.noShowRate.toFixed(1) + '%'} sub="Of booked appointments" delta={k.noShowRate <= 3 ? 'healthy' : 'high'} deltaPositive={k.noShowRate <= 3}
                 info="% of appointments where customer didn't show up and didn't cancel. Direct revenue loss. Benchmark under 3%."/>
        <KpiTile icon="percent"  iconColor="#c084fc" label="Royalty Projection" value={'~' + fmtMoney(k.royalties)} sub={`Modeled on ${net.franchised} franchised shops`}
                 info="Projected royalty revenue, modeled from each franchisee's reported net sales × their agreement's royalty rate. This is an estimate — actual collected royalties depend on per-agreement terms, reporting timing, and reconciliation."/>
        <KpiTile icon="star"     iconColor="#f472b6" label="Brand NPS"        value={k.nps.toString()} sub="Post-visit surveys" delta="+3 vs last period" deltaPositive
                 info="Net Promoter Score (-100 to +100) from post-visit surveys collected in the customer portal. 70+ is excellent for service brands."/>
        <KpiTile icon="shield"   iconColor="#a78bfa" label="Compliance"       value={k.complianceOpen.toString() + ' open'} sub="CASL · PIPEDA · brand standards" delta={k.complianceOpen <= 5 ? 'in control' : 'review'} deltaPositive={k.complianceOpen <= 5}
                 info="Open compliance items across CASL (anti-spam consent), PIPEDA (privacy), and brand standards. Each item links to the responsible location."/>
        <KpiTile icon="gift"     iconColor="#22d3ee" label="Loyalty Penetration" value="72%" sub="Active members / customers" delta="+2.4pp" deltaPositive
                 info="Share of network customers who are active loyalty members. Tracks the health of your loyalty program across all locations."/>
      </div>

      <div className="hero-foot">
        <div className="hero-foot-pill">
          <span className="dot" style={{ background:'#34d399' }}/>
          <b>Network healthy</b>
          <span>Utilization {k.utilization.toFixed(1)}% · Revenue/hr ${k.revPerHour.toFixed(2)} · NPS {k.nps}</span>
        </div>
        <button className="link-btn" data-live="1" onClick={() => window.dispatchEvent(new CustomEvent('hb:nav', { detail: 'reports' }))}>View executive report <Icon name="arrow-right" size={13} stroke={2.2} /></button>
      </div>
    </section>
  );
};

Object.assign(window, { HeroKpiStrip, fmtMoney, fmtMoneyFull, fmtPct, fmtHrs, InfoDot });
