// Use Cases — ecosystem viz + interactive explorer

const USE_CASES = [
  {
    id: 'legal',
    name: 'Legal AI',
    icon: 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2',
    beforeSteps: ['Contract upload', 'Rented LLM draft', 'Lawyer edits', 'Lost signal'],
    beforeProblem: 'Owns contract workflows, lawyer edits, rejected clauses — but not the model behavior. Every clause runs through a rented LLM.',
    afterSteps: ['Capture edits', 'Build eval sets', 'Fine-tune model', 'Owned legal AI'],
    signals: ['Lawyer edits → SFT examples', 'Rejected clauses → hard negatives', 'Contract workflows → eval sets', 'Domain data → owned legal model'],
    afterSummary: 'Lawyer edits → SFT examples. Rejected clauses → hard negatives. Contract workflows → eval sets. Domain data → owned legal model.',
    outcomes: ['Lower inference cost', 'Stronger domain behavior', 'Safer deployment', 'Compounding legal moat'],
  },
  {
    id: 'support',
    name: 'Customer Support AI',
    icon: 'M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z',
    beforeSteps: ['Ticket intake', 'Generic LLM reply', 'Escalation', 'CSAT lost'],
    beforeProblem: 'Collects conversations, escalations, failed answers, CSAT signals — but none of it becomes model behavior. The wrapper stays frozen.',
    afterSteps: ['Route tickets', 'Train on failures', 'Optimize routing', 'Owned support AI'],
    signals: ['Routine tickets → low-cost owned models', 'Failed answers → eval cases', 'Escalations → training signals', 'CSAT → routing logic'],
    afterSummary: 'Routine tickets → low-cost owned models. Failed answers → eval cases. Escalations → training signals. CSAT → routing logic.',
    outcomes: ['Lower cost', 'Better accuracy', 'Faster resolution', 'Improving support intelligence'],
  },
  {
    id: 'code',
    name: 'Coding Agent',
    icon: 'M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4',
    beforeSteps: ['Prompt → patch', 'Frontier model', 'Test failures', 'No memory'],
    beforeProblem: 'Relies on frontier models but can\'t capture accepted patches, failed tests, reverted diffs, and long-running execution state.',
    afterSteps: ['Trace execution', 'Capture outcomes', 'Build eval gates', 'Owned code agent'],
    signals: ['Accepted patches → positive examples', 'Failed tests → hard negatives', 'Tool traces → workflow memory', 'Runtime sessions → eval data'],
    afterSummary: 'Accepted patches → positive examples. Failed tests → hard negatives. Tool traces → workflow memory. Runtime sessions → eval data.',
    outcomes: ['Better code behavior', 'Safer execution', 'Stronger workflow control', 'Routing grounded in outcomes'],
  },
  {
    id: 'health',
    name: 'Healthcare Intake',
    icon: 'M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z',
    beforeSteps: ['Patient intake', 'Generic triage', 'Nurse override', 'No audit trail'],
    beforeProblem: 'Needs safety, auditability, human review, escalation handling, domain-specific behavior — but runs on a generic frontier model.',
    afterSteps: ['Human-in-loop', 'Capture corrections', 'Eval gates', 'Owned health AI'],
    signals: ['Nurse edits → training data', 'Triage corrections → eval cases', 'Escalations → deployment gates', 'Outcomes → audit trail'],
    afterSummary: 'Nurse edits, triage corrections, escalation decisions, patient workflow outcomes → training data, eval data, and deployment gates.',
    outcomes: ['Safer deployment', 'Human-in-loop control', 'Stronger eval discipline', 'Traceable healthcare intelligence'],
  },
  {
    id: 'sales',
    name: 'Sales / GTM AI',
    icon: 'M13 7h8m0 0v8m0-8l-8 8-4-4-6 6',
    beforeSteps: ['Outbound draft', 'Rented messaging', 'Reply patterns', 'CRM silo'],
    beforeProblem: 'Collects outbound sequences, reply patterns, objections, call notes, conversion outcomes — but the model behavior remains rented.',
    afterSteps: ['Capture wins/losses', 'Preference data', 'Route by signal', 'Owned GTM AI'],
    signals: ['Successful sequences → preference data', 'Failed replies → hard negatives', 'Conversion signals → routing logic', 'CRM workflows → eval cases'],
    afterSummary: 'Successful sequences → preference data. Failed replies → hard negatives. Conversion signals → routing logic. CRM workflows → eval cases.',
    outcomes: ['Higher conversion', 'Stronger domain messaging', 'Lower inference cost', 'Customer-owned GTM intelligence'],
  },
  {
    id: 'creator',
    name: 'Creator / Marketing AI',
    icon: 'M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z',
    beforeSteps: ['Generate draft', 'Brand mismatch', 'Manual edits', 'No learning'],
    beforeProblem: 'Collects accepted content, rejected outputs, campaign conversions, brand edits, tone preferences — but the intelligence remains rented.',
    afterSteps: ['Capture preferences', 'Brand alignment', 'Route by outcome', 'Owned creative AI'],
    signals: ['Accepted outputs → preference data', 'Rejected drafts → hard negatives', 'Conversion signals → routing logic', 'Brand edits → owned behavior'],
    afterSummary: 'Accepted outputs → preference data. Rejected drafts → hard negatives. Conversion signals → routing logic. Brand edits → owned behavior.',
    outcomes: ['Brand-specific models', 'Lower generation cost', 'Better creative consistency', 'Compounding customer intelligence'],
  },
];

const UseCaseIcon = ({ path, size = 20 }) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" width={size} height={size}>
    <path d={path} />
  </svg>
);

const FlowDiagram = ({ steps, variant = 'before' }) => (
  <div className={`uc-flow uc-flow--${variant}`}>
    {steps.map((step, i) => (
      <React.Fragment key={step}>
        {i > 0 && <div className="uc-flow-connector" aria-hidden="true"><span /></div>}
        <div className="uc-flow-node">
          <span className="uc-flow-node-num">{String(i + 1).padStart(2, '0')}</span>
          <span className="uc-flow-node-label">{step}</span>
        </div>
      </React.Fragment>
    ))}
  </div>
);

// Even circular orbit around Model OS center
const ORBIT_RADIUS = 31;
const HUB_RADIUS = 13;
const LINE_INSET = 4;

const getOrbitXY = (i, count = USE_CASES.length) => {
  const angle = (i / count) * Math.PI * 2 - Math.PI / 2;
  return {
    x: 50 + ORBIT_RADIUS * Math.cos(angle),
    y: 50 + ORBIT_RADIUS * Math.sin(angle),
  };
};

const getLineStart = (nx, ny) => {
  const dx = nx - 50;
  const dy = ny - 50;
  const dist = Math.hypot(dx, dy) || 1;
  return {
    x1: 50 + (dx / dist) * HUB_RADIUS,
    y1: 50 + (dy / dist) * HUB_RADIUS,
  };
};

const getLineEnd = (nx, ny) => {
  const dx = nx - 50;
  const dy = ny - 50;
  const dist = Math.hypot(dx, dy) || 1;
  return {
    x2: nx - (dx / dist) * LINE_INSET,
    y2: ny - (dy / dist) * LINE_INSET,
  };
};

const renderEcoLine = (uc, i, activeId, hoveredId, isActiveLayer) => {
  const { x: nx, y: ny } = getOrbitXY(i);
  const isLit = uc.id === activeId || uc.id === hoveredId;
  if (isActiveLayer !== isLit) return null;
  const { x1, y1 } = getLineStart(nx, ny);
  const { x2, y2 } = getLineEnd(nx, ny);
  return (
    <line
      key={isActiveLayer ? `${uc.id}-active` : uc.id}
      x1={x1}
      y1={y1}
      x2={x2}
      y2={y2}
      className={`uc-eco-line ${isLit ? 'uc-eco-line--active' : ''}`}
    />
  );
};

const ORBIT_PATH = (() => {
  const steps = 64;
  let d = '';
  for (let s = 0; s <= steps; s += 1) {
    const angle = (s / steps) * Math.PI * 2 - Math.PI / 2;
    const x = 50 + ORBIT_RADIUS * Math.cos(angle);
    const y = 50 + ORBIT_RADIUS * Math.sin(angle);
    d += `${s === 0 ? 'M' : 'L'} ${x.toFixed(2)} ${y.toFixed(2)} `;
  }
  return d + 'Z';
})();

const EcosystemViz = ({ activeId, onSelect, hoveredId, onHover }) => (
    <div className="uc-ecosystem uc-ecosystem--orbit" aria-hidden="false">
      <svg className="uc-eco-lines uc-eco-lines--orbit uc-eco-lines--back" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
        <defs>
          <linearGradient id="ucEcoLineGrad" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#6080ff" stopOpacity="0.9" />
            <stop offset="50%" stopColor="#b264ff" stopOpacity="0.95" />
            <stop offset="100%" stopColor="#ff6fbf" stopOpacity="0.85" />
          </linearGradient>
        </defs>
        <path d={ORBIT_PATH} className="uc-eco-orbit-ring uc-eco-orbit-ring--outer" />
        {USE_CASES.map((uc, i) => renderEcoLine(uc, i, activeId, hoveredId, false))}
        <circle cx="50" cy="50" r={HUB_RADIUS} className="uc-eco-orbit-ring" />
      </svg>

      <div className="uc-eco-hub uc-eco-hub--orbit">
        <div className="uc-eco-hub-inner uc-eco-hub-inner--enter">
          <img src="assets/mini logo (1).png" alt="" className="uc-eco-hub-logo" />
          <span className="uc-eco-hub-label">Model OS</span>
        </div>
        <div className="uc-eco-hub-pulse" aria-hidden="true" />
      </div>

      <svg className="uc-eco-lines uc-eco-lines--orbit uc-eco-lines--front" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
        {USE_CASES.map((uc, i) => renderEcoLine(uc, i, activeId, hoveredId, true))}
      </svg>

      {USE_CASES.map((uc, i) => {
        const { x, y } = getOrbitXY(i);
        const isActive = uc.id === activeId;
        const isHovered = uc.id === hoveredId;
        const enterDelay = 0.12 + i * 0.09;
        const floatStart = enterDelay + 0.95;

        return (
          <button
            key={uc.id}
            type="button"
            className={`uc-eco-node uc-eco-node--orbit ${isActive ? 'uc-eco-node--active' : ''} ${isHovered ? 'uc-eco-node--hover' : ''}`}
            style={{
              left: `${x}%`,
              top: `${y}%`,
              '--float-delay': `${i * 0.55}s`,
              '--enter-delay': `${enterDelay}s`,
              '--float-start': `${floatStart}s`,
            }}
            onClick={() => onSelect(i)}
            onMouseEnter={() => onHover(uc.id)}
            onMouseLeave={() => onHover(null)}
            aria-label={`Explore ${uc.name}`}
            aria-pressed={isActive}
          >
            <span className="uc-eco-node-enter">
              <span className="uc-eco-node-float">
                <span className="uc-eco-node-icon">
                  <UseCaseIcon path={uc.icon} size={18} />
                </span>
                <span className="uc-eco-node-name">{uc.name}</span>
              </span>
            </span>
          </button>
        );
      })}
    </div>
);

const UseCaseExplorer = ({ activeIndex, onSelect, paused }) => {
  const active = USE_CASES[activeIndex];

  return (
    <div className="uc-explorer">
      <div className="uc-explorer-nav">
        <div className="uc-explorer-nav-head">
          <span className="label">Explore</span>
          {!paused && <span className="uc-explorer-autoplay"><span className="uc-explorer-autoplay-dot" />Auto</span>}
        </div>
        <ul className="uc-explorer-list" role="tablist">
          {USE_CASES.map((uc, i) => (
            <li key={uc.id}>
              <button
                type="button"
                role="tab"
                aria-selected={i === activeIndex}
                className={`uc-explorer-item ${i === activeIndex ? 'uc-explorer-item--active' : ''}`}
                onClick={() => onSelect(i)}
              >
                <span className="uc-explorer-item-icon">
                  <UseCaseIcon path={uc.icon} size={18} />
                </span>
                <span className="uc-explorer-item-name">{uc.name}</span>
                <span className="uc-explorer-item-bar" aria-hidden="true" />
              </button>
            </li>
          ))}
        </ul>
      </div>

      <div className="uc-explorer-panel" role="tabpanel">
        <div key={active.id} className="uc-explorer-card uc-explorer-card--enter">
          <div className="uc-explorer-card-head">
            <span className="uc-explorer-card-icon">
              <UseCaseIcon path={active.icon} size={22} />
            </span>
            <h3>{active.name}</h3>
          </div>

          <div className="uc-explorer-section uc-explorer-section--before">
            <div className="uc-explorer-section-label">
              <span className="uc-explorer-tag uc-explorer-tag--before">Before</span>
              <span>Workflow trapped in a wrapper</span>
            </div>
            <FlowDiagram steps={active.beforeSteps} variant="before" />
            <p className="uc-explorer-problem">{active.beforeProblem}</p>
          </div>

          <div className="uc-explorer-divider" aria-hidden="true">
            <span className="uc-explorer-divider-line" />
            <span className="uc-explorer-divider-icon">↓</span>
            <span className="uc-explorer-divider-line" />
          </div>

          <div className="uc-explorer-section uc-explorer-section--after">
            <div className="uc-explorer-section-label">
              <span className="uc-explorer-tag uc-explorer-tag--after">With Model OS</span>
              <span>Workflow data → owned intelligence</span>
            </div>
            <FlowDiagram steps={active.afterSteps} variant="after" />
            <ul className="uc-explorer-signals">
              {active.signals.map((signal) => (
                <li key={signal}>
                  <span className="uc-explorer-signal-dot" />
                  {signal}
                </li>
              ))}
            </ul>
          </div>

          <div className="uc-explorer-outcomes">
            {active.outcomes.map((outcome) => (
              <span key={outcome} className="uc-explorer-outcome">{outcome}</span>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

const UseCases = () => {
  const [activeIndex, setActiveIndex] = React.useState(0);
  const [hoveredId, setHoveredId] = React.useState(null);
  const [paused, setPaused] = React.useState(false);

  React.useEffect(() => {
    if (paused) return undefined;
    const timer = setInterval(() => {
      setActiveIndex((i) => (i + 1) % USE_CASES.length);
    }, 4000);
    return () => clearInterval(timer);
  }, [paused, activeIndex]);

  const handleSelect = (index) => {
    setActiveIndex(index);
  };

  return (
    <section className="section uc-section" id="usecases" data-screen-label="07 Use Cases">
      <div className="uc-section-bg" aria-hidden="true">
        <div className="uc-section-grid" />
        <div className="uc-section-glow uc-section-glow--1" />
        <div className="uc-section-glow uc-section-glow--2" />
      </div>

      <div className="wrap uc-wrap">
        <div
          className="uc-interactive"
          onMouseEnter={() => setPaused(true)}
          onMouseLeave={() => setPaused(false)}
        >
          <div className="uc-hero">
            <div className="s-head uc-hero-copy">
              <span className="label">/ 06 — Use cases</span>
              <h2>Every vertical AI app has a hidden <span className="gradient">model moat</span>.</h2>
              <p className="lede">
                Inside its usage data. Model OS extracts it — converting workflow signals from every vertical into owned models and intelligence assets.
              </p>
            </div>

            <EcosystemViz
              activeId={USE_CASES[activeIndex].id}
              onSelect={handleSelect}
              hoveredId={hoveredId}
              onHover={setHoveredId}
            />
          </div>

          <UseCaseExplorer
            activeIndex={activeIndex}
            onSelect={handleSelect}
            paused={paused}
          />
        </div>
      </div>
    </section>
  );
};

window.UseCases = UseCases;
