// Program Studio — Deploy tab
// Phased rollout: governorate canary → traffic % → full rollout
// Live KPI watchers with auto-rollback rules.

function StudioDeploy({ programMeta, rules, parentRules, lib }) {
  const [phase, setPhase] = React.useState(1); // 1=canary, 2=expanded, 3=full
  const [trafficPct, setTrafficPct] = React.useState(10);
  const [governorates, setGovernorates] = React.useState(["Al Batinah North"]);
  const [autoRollback, setAutoRollback] = React.useState(true);

  return (
    <div className="studio-deploy">
      <div className="deploy-head">
        <div>
          <div className="label-eyebrow">Phased rollout</div>
          <h2 className="h2" style={{marginTop:4, fontSize:26}}>Ship the change safely.</h2>
          <p className="muted text-14" style={{maxWidth:560, marginTop:8}}>
            Roll out gradually by governorate and traffic %. Live KPIs are watched against baselines, with automatic rollback if the change degrades any guardrail.
          </p>
        </div>
        <div className="row" style={{gap:8}}>
          <button className="btn ghost"><Icon name="eye" size={13}/> Preview before/after</button>
          <button className="btn copper lg"><Icon name="send" size={14}/> Promote to next phase</button>
        </div>
      </div>

      <div className="deploy-phases">
        <PhaseCard
          n={1} current={phase >= 1} active={phase === 1} done={phase > 1}
          title="Sohar canary"
          subtitle="10% of incoming Sohar applications"
          when="Live for 2h 14m"
          metrics={[
            { label: "STP rate", from: "67.2%", to: "70.8%", trend: "up", ok: true },
            { label: "p95 decision time", from: "1.6s", to: "1.4s", trend: "down", ok: true },
            { label: "Reject rate", from: "8.1%", to: "5.4%", trend: "down", ok: true },
            { label: "90-day delinquency proxy", from: "1.8%", to: "1.7%", trend: "flat", ok: true },
          ]}
          onPromote={() => setPhase(2)}
        />
        <PhaseCard
          n={2} active={phase === 2}
          title="All governorates · 25%"
          subtitle="Sohar + 4 governorates · 25% traffic"
          when={phase >= 2 ? "Live" : "Waiting on canary · auto-promote at 24h"}
          metrics={[]}
          locked={phase < 2}
        />
        <PhaseCard
          n={3} active={phase === 3}
          title="Full rollout"
          subtitle="100% of traffic · all governorates"
          when="Waiting on phase 2"
          metrics={[]}
          locked={phase < 3}
        />
      </div>

      <div className="deploy-grid">

        <div className="card card-pad">
          <div className="label-eyebrow"><Icon name="shield" size={11}/> Guardrails</div>
          <div className="title" style={{fontSize:15, marginTop:4}}>Auto-rollback if breached</div>
          <div className="guardrail-list">
            <Guardrail icon="trending" name="STP rate" threshold="≥ 65%" current="70.8%" status="ok"/>
            <Guardrail icon="alert" name="Reject rate" threshold="≤ 12%" current="5.4%" status="ok"/>
            <Guardrail icon="clock" name="p95 decision time" threshold="≤ 3.0s" current="1.4s" status="ok"/>
            <Guardrail icon="scale" name="DTI exceptions (manual)" threshold="≤ 50/day" current="14" status="ok"/>
            <Guardrail icon="plug" name="Integration error rate" threshold="≤ 1%" current="0.3%" status="ok"/>
          </div>
        </div>

        <div className="card card-pad deploy-live">
          <div className="row" style={{justifyContent:"space-between"}}>
            <div>
              <div className="label-eyebrow"><span className="pulse-dot"/> Live · last 2 hours</div>
              <div className="title" style={{fontSize:15, marginTop:4}}>Sohar canary metrics</div>
            </div>
            <button className="btn ghost sm"><Icon name="bar_chart" size={13}/> Open dashboard</button>
          </div>
          <div className="deploy-chart">
            <svg viewBox="0 0 400 140" preserveAspectRatio="none" style={{width:"100%", height:140}}>
              <defs>
                <linearGradient id="g1" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#1b4149" stopOpacity="0.35"/>
                  <stop offset="100%" stopColor="#1b4149" stopOpacity="0"/>
                </linearGradient>
              </defs>
              {/* baseline */}
              <line x1="0" y1="65" x2="400" y2="65" stroke="#e3ddd4" strokeDasharray="4 4"/>
              <text x="6" y="60" fontSize="9" fill="#98928b">v4.2 baseline 67%</text>
              {/* area */}
              <path d="M 0 110 L 20 100 L 40 92 L 60 85 L 80 80 L 100 72 L 120 65 L 140 60 L 160 55 L 180 50 L 200 48 L 220 45 L 240 42 L 260 40 L 280 38 L 300 36 L 320 34 L 340 33 L 360 32 L 380 31 L 400 30 L 400 140 L 0 140 Z" fill="url(#g1)"/>
              <path d="M 0 110 L 20 100 L 40 92 L 60 85 L 80 80 L 100 72 L 120 65 L 140 60 L 160 55 L 180 50 L 200 48 L 220 45 L 240 42 L 260 40 L 280 38 L 300 36 L 320 34 L 340 33 L 360 32 L 380 31 L 400 30" stroke="#1b4149" strokeWidth="2" fill="none"/>
              <circle cx="400" cy="30" r="4" fill="#1b4149"/>
              <text x="370" y="22" fontSize="10" fontWeight="700" fill="#1b4149">70.8%</text>
            </svg>
            <div className="deploy-chart-x">
              <span className="tiny muted">2h ago</span>
              <span className="tiny muted">now</span>
            </div>
          </div>
          <div className="deploy-events">
            <div className="deploy-event">
              <span className="statusdot ok"/>
              <span className="text-13"><strong>Canary stable.</strong> STP rate +3.6pp over baseline — within guardrails.</span>
              <span className="tiny muted">2m ago</span>
            </div>
            <div className="deploy-event">
              <span className="statusdot ok"/>
              <span className="text-13">First 100 cases processed · 71 STP, 24 review, 5 reject</span>
              <span className="tiny muted">2h ago</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function PhaseCard({ n, current, active, done, title, subtitle, when, metrics, locked, onPromote }) {
  return (
    <div className={`phase-card ${active ? "active" : ""} ${done ? "done" : ""} ${locked ? "locked" : ""}`}>
      <div className="phase-head">
        <div className={`phase-pip ${done ? "done" : active ? "active" : "pending"}`}>
          {done ? <Icon name="check" size={14}/> : n}
        </div>
        <div style={{flex:1}}>
          <div className="text-14" style={{fontWeight:700}}>{title}</div>
          <div className="tiny muted">{subtitle}</div>
        </div>
        {active && <span className="pill copper"><span className="pulse-dot"/> Live</span>}
        {done && <span className="pill ok">Promoted</span>}
        {locked && <span className="pill ghost">Locked</span>}
      </div>
      <div className="phase-when">{when}</div>
      {metrics && metrics.length > 0 && (
        <div className="phase-metrics">
          {metrics.map((m, i) => (
            <div key={i} className="phase-metric">
              <span className="tiny muted">{m.label}</span>
              <div className="row" style={{gap:6, marginTop:2}}>
                <span className="mono text-12 muted" style={{textDecoration:"line-through"}}>{m.from}</span>
                <Icon name="arrow_right" size={10} style={{color:"var(--muted)"}}/>
                <span className="mono text-13" style={{fontWeight:700, color: m.ok ? "var(--ok)" : "var(--warn)"}}>{m.to}</span>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function Guardrail({ icon, name, threshold, current, status }) {
  return (
    <div className="guardrail-row">
      <div className={`guardrail-icon status-${status}`}><Icon name={icon} size={13}/></div>
      <div style={{flex:1}}>
        <div className="text-13" style={{fontWeight:600}}>{name}</div>
        <div className="tiny muted">Threshold: {threshold}</div>
      </div>
      <div className="row" style={{gap:8, alignItems:"center"}}>
        <span className="mono text-13" style={{fontWeight:700, color: status === "ok" ? "var(--ok)" : "var(--warn)"}}>{current}</span>
        <span className={`statusdot ${status}`}/>
      </div>
    </div>
  );
}

window.StudioDeploy = StudioDeploy;
