// Shared UI components
const { useState, useEffect, useRef, useCallback } = React;

function ProgressBar({ phase }) {
  const idx = window.phaseIndex(phase);
  const pct = Math.round((idx / (window.PHASES.length - 1)) * 100);
  return (
    <div className="progress" aria-hidden="true">
      <div className="progress-fill" style={{ width: pct + "%" }} />
    </div>
  );
}

function AppTop({ phase, onRestart }) {
  return (
    <div className="app-top">
      <div className="brand">The Stress Reset</div>
      <ProgressBar phase={phase} />
      <button className="tiny-link" onClick={onRestart} style={{ fontSize: 11, padding: 0 }}>
        Restart
      </button>
    </div>
  );
}

function PrimaryButton({ children, onClick, disabled, ...rest }) {
  return (
    <button className="btn btn-primary btn-block" onClick={onClick} disabled={disabled} {...rest}>
      {children}
    </button>
  );
}

function GhostButton({ children, onClick, ...rest }) {
  return (
    <button className="btn btn-ghost btn-block" onClick={onClick} {...rest}>
      {children}
    </button>
  );
}

function Eyebrow({ children }) {
  return <div className="eyebrow">{children}</div>;
}

// SVG Gauge — animated fill
function Gauge({ intensity, label }) {
  // semicircle gauge: 0 (low) -> 1 (critical)
  const [animVal, setAnimVal] = useState(0);
  useEffect(() => {
    const t = setTimeout(() => setAnimVal(intensity), 200);
    return () => clearTimeout(t);
  }, [intensity]);

  // Arc geometry
  const r = 100;
  const cx = 120;
  const cy = 120;
  const startA = Math.PI; // left
  const endA = 0; // right
  const totalArc = startA - endA; // PI
  const angle = startA - totalArc * animVal;

  const arcPath = (a1, a2) => {
    const x1 = cx + r * Math.cos(a1);
    const y1 = cy - r * Math.sin(a1);
    const x2 = cx + r * Math.cos(a2);
    const y2 = cy - r * Math.sin(a2);
    const large = Math.abs(a1 - a2) > Math.PI ? 1 : 0;
    return `M ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2}`;
  };

  // Color blends through the bands
  const fillColor = animVal < 0.4 ? "#5C7A5B"
    : animVal < 0.6 ? "#C49A2C"
    : animVal < 0.85 ? "#C45A2C"
    : "#8E3F1E";

  // Tick positions
  const ticks = [0.25, 0.5, 0.75];
  return (
    <svg viewBox="0 0 240 150" width="240" height="150" aria-label={`Stress gauge: ${label}`}>
      {/* Track */}
      <path d={arcPath(startA, endA)} fill="none" stroke="#E5DDD0" strokeWidth="14" strokeLinecap="round"/>
      {/* Fill */}
      <path
        d={arcPath(startA, angle)}
        fill="none"
        stroke={fillColor}
        strokeWidth="14"
        strokeLinecap="round"
        style={{ transition: "all 1400ms cubic-bezier(.4,0,.2,1)" }}
      />
      {/* Ticks */}
      {ticks.map((t, i) => {
        const a = startA - totalArc * t;
        const x1 = cx + (r - 16) * Math.cos(a);
        const y1 = cy - (r - 16) * Math.sin(a);
        const x2 = cx + (r + 16) * Math.cos(a);
        const y2 = cy - (r + 16) * Math.sin(a);
        return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke="#C9BFAE" strokeWidth="1"/>;
      })}
      {/* Needle */}
      <g style={{ transition: "transform 1400ms cubic-bezier(.4,0,.2,1)", transformOrigin: `${cx}px ${cy}px`, transform: `rotate(${(1 - animVal) * 180 - 90}deg)` }}>
        <line x1={cx} y1={cy} x2={cx} y2={cy - r + 18} stroke="#1C1816" strokeWidth="3" strokeLinecap="round" />
        <circle cx={cx} cy={cy} r="8" fill="#1C1816" />
      </g>
      {/* Endpoint labels */}
      <text x="14" y="140" fontSize="11" fontFamily="Inter" fill="#6E635A">Low</text>
      <text x="216" y="140" fontSize="11" fontFamily="Inter" fill="#6E635A" textAnchor="end">Critical</text>
    </svg>
  );
}

// Persistent medical disclaimer footer
function DisclaimerFooter() {
  const [expanded, setExpanded] = useState(false);
  return (
    <footer className="disclaimer-footer">
      <button
        className="df-toggle"
        onClick={() => setExpanded(!expanded)}
        aria-expanded={expanded}
      >
        <span className="df-mark" aria-hidden="true">
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="12" cy="12" r="10"/>
            <line x1="12" y1="8" x2="12" y2="12"/>
            <line x1="12" y1="16" x2="12.01" y2="16"/>
          </svg>
        </span>
        <span className="df-line">
          <strong>Educational content only.</strong> Not professional medical or psychological advice.
        </span>
        <span className={`df-chev ${expanded ? "open" : ""}`} aria-hidden="true">▾</span>
      </button>
      {expanded && (
        <div className="df-body">
          <p>
            This companion app is for personal reflection and education only. The content, tools, exercises and scores presented here are <strong>not</strong> a substitute for advice, diagnosis or treatment from a registered medical doctor, psychiatrist, psychologist, counsellor or other qualified health professional.
          </p>
          <p>
            If you are experiencing severe stress, persistent low mood, anxiety, panic, suicidal thoughts, or any mental or physical symptom that worries you, please consult a qualified professional. In a crisis, contact emergency services or a recognised crisis line in your country.
          </p>
          <p className="df-credit">
            The Stress Reset
          </p>
        </div>
      )}
    </footer>
  );
}

Object.assign(window, {
  ProgressBar, AppTop, PrimaryButton, GhostButton, Eyebrow, Gauge, DisclaimerFooter,
});
