/* ───────────────────────────────────────────────────────────────────────────
   Clarity360 — shared product components
   Markup + classNames only; the visual system lives in the main HTML <style>.
   Exported to window so each surface file can use them.
   ─────────────────────────────────────────────────────────────────────────── */

const D = window.DRIVERS;

// ── DriverChip ── small pill: dot + code, driver-colored ─────────────────────
function DriverChip({ code, label = false, big = false }) {
  const d = D[code];
  if (!d) return null;
  return (
    <span className={'dchip ' + d.cls + (big ? ' dchip-big' : '')}>
      <span className="ddot" />
      {code}{d.hub ? ' ✶' : ''}{label ? ' · ' + d.short : ''}
    </span>
  );
}

// ── TierChip ── evidence tier tag ────────────────────────────────────────────
const TIER_LABEL = { T1: 'Peer-reviewed foundational', T2: 'Translational / clinical consensus', T3: 'Professional society / patient org' };
function TierChip({ tier }) {
  if (!tier) return null;
  // tiers like "T2/T3" render as-is
  const base = tier.split('/')[0];
  return <span className={'tier tier-' + base.toLowerCase()} title={TIER_LABEL[base] || ''}>{tier}</span>;
}

// ── DriverBar ── one driver, weighted ────────────────────────────────────────
function DriverBar({ code, weight, state, tier, animate = true }) {
  const d = D[code];
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current) return;
    if (animate) {
      ref.current.style.width = '0%';
      requestAnimationFrame(() => requestAnimationFrame(() => { if (ref.current) ref.current.style.width = Math.round(weight * 100) + '%'; }));
    } else {
      ref.current.style.width = Math.round(weight * 100) + '%';
    }
  }, [weight, animate]);
  const lead = /lead|primary/i.test(state || '');
  return (
    <div className="dbar">
      <div className="dbar-code" style={{ color: d.color, background: d.tint, borderColor: d.color }}>{code}{d.hub ? ' ✶' : ''}</div>
      <div className="dbar-track">
        <i ref={ref} className="dbar-fill" style={{ background: d.color }} />
      </div>
      <div className="dbar-meta">
        <span className="dbar-state" style={{ color: lead ? d.color : 'var(--bf-muted)', fontWeight: lead ? 700 : 500 }}>{state}</span>
        {tier && <TierChip tier={tier} />}
      </div>
    </div>
  );
}

// ── DriverProfile ── the ranked stack ────────────────────────────────────────
function DriverProfile({ drivers, animate = true, showTier = true }) {
  return (
    <div className="dprofile">
      {drivers.map((d) => (
        <DriverBar key={d.code} code={d.code} weight={d.weight} state={d.state} tier={showTier ? d.tier : null} animate={animate} />
      ))}
    </div>
  );
}

// ── Avatar ───────────────────────────────────────────────────────────────────
function Avatar({ who, persona, size = 34 }) {
  // who: 'lena' (educator) or persona id
  const isLena = who === 'lena';
  const initial = isLena ? 'L' : (persona ? persona.initial : '·');
  return (
    <div className={'avatar ' + (isLena ? 'av-lena' : 'av-you')} style={{ width: size, height: size, fontSize: size * 0.38 }}>
      {initial}
    </div>
  );
}

// ── SurfaceHead ── consistent surface header ─────────────────────────────────
function SurfaceHead({ eyebrow, title, sub, aside }) {
  return (
    <div className="surface-head">
      <div>
        {eyebrow && <div className="surface-eyebrow">{eyebrow}</div>}
        <h1 className="surface-title">{title}</h1>
        {sub && <p className="surface-sub">{sub}</p>}
      </div>
      {aside && <div className="surface-aside">{aside}</div>}
    </div>
  );
}

// ── CalibrationStrip ── the personal-tailoring layer, summarized ─────────────
// Observation 5: the same physiology, delivered to fit this person.
function CalibrationStrip({ persona, compact = false }) {
  const c = persona.calibration;
  const order = ['literacy', 'comms', 'readiness', 'agency', 'efficacy', 'sdoh'];
  return (
    <div className={'calib-strip' + (compact ? ' calib-compact' : '')}>
      {order.map((k) => {
        const inst = window.CALIBRATION_INSTRUMENTS.find((i) => i.key === k);
        return (
          <div className="calib-item" key={k} title={inst.instrument + ' → ' + inst.drives}>
            <span className="calib-name">{inst.name}</span>
            <span className="calib-val">{c[k].value}</span>
          </div>
        );
      })}
    </div>
  );
}

// ── ConflictCard ── a preserved controversy (never flattened) ────────────────
function ConflictCard({ topic, position, counter, significance }) {
  return (
    <div className="conflict">
      <div className="conflict-topic">{topic}</div>
      <div className="conflict-cols">
        <div className="conflict-col">
          <span className="conflict-lab">Common read</span>
          <p>{position}</p>
        </div>
        <div className="conflict-col counter">
          <span className="conflict-lab">What the evidence says</span>
          <p>{counter}</p>
        </div>
      </div>
      <div className="conflict-sig"><span>↳ why it changes the plan</span> {significance}</div>
    </div>
  );
}

// ── small helpers ─────────────────────────────────────────────────────────────
function Eyebrow({ children, color }) {
  return <div className="eyebrow" style={color ? { color } : null}>{children}</div>;
}

function StickyNote({ eyebrow, children, tone = 'teal', rotate = -1.2 }) {
  return (
    <div className={'sticky-note tone-' + tone} style={{ transform: `rotate(${rotate}deg)` }}>
      {eyebrow && <div className="sn-eyebrow">{eyebrow}</div>}
      <div className="sn-body">{children}</div>
    </div>
  );
}

// ── the canonical walkthrough — one logical click-path through the product ───
// Mirrors the proposal's happy path: intake/synthesis → Story → Plan →
// editorial gate → care-team handoff. Every surface advances along this order.
window.FLOW = [
  { key: 'conversation', label: 'Conversation',       audience: 'the individual', beat: 'Intake + synthesis, revealed in dialogue' },
  { key: 'engine',       label: 'Synthesis engine',   audience: 'how it reads',   beat: 'How the engine read the library to get there' },
  { key: 'story',        label: 'My Health Story',     audience: 'the individual', beat: 'The synthesis, delivered as narrative' },
  { key: 'plan',         label: 'My Action Plan',      audience: 'the individual', beat: 'Six levers, three tiers, what to do' },
  { key: 'editorial',    label: 'Editorial review',    audience: 'the credibility layer', beat: 'A human approves it before it ships' },
  { key: 'care',         label: 'Care Team Companion', audience: 'for the care team', beat: 'What the clinician receives' },
];

function FlowFooter({ current, go }) {
  const FLOW = window.FLOW;
  const idx = FLOW.findIndex((f) => f.key === current);
  const prev = FLOW[idx - 1];
  const next = FLOW[idx + 1];
  return (
    <div className="flow-footer">
      <div className="ff-progress">
        <div className="ff-dots">
          {FLOW.map((f, i) => (
            <button key={f.key} className={'ff-dot' + (i === idx ? ' on' : i < idx ? ' done' : '')}
                    onClick={() => go(f.key)} title={(i + 1) + '. ' + f.label} />
          ))}
        </div>
        <span className="ff-step">Step {idx + 1} of {FLOW.length} · {FLOW[idx].label}</span>
      </div>
      <div className="ff-nav">
        {prev && <button className="btn ghost" onClick={() => go(prev.key)}>← {prev.label}</button>}
        {next
          ? <button className="btn primary" onClick={() => go(next.key)}>Next · {next.label} →</button>
          : <button className="btn primary" onClick={() => go('conversation')}>↻ Start the walkthrough over</button>}
      </div>
    </div>
  );
}

Object.assign(window, {
  DriverChip, TierChip, DriverBar, DriverProfile, Avatar,
  SurfaceHead, CalibrationStrip, ConflictCard, Eyebrow, StickyNote, FlowFooter,
});
