// ─── HOMEWORK / RANKINGS — shared helpers + voice memo control ──

const PARENTS = [
  { id:"jamie", label:"Jamie", initial:"J" },
  { id:"tom",   label:"Tom",   initial:"T" },
];

// Voice-to-text using browser SpeechRecognition. Falls back gracefully.
function VoiceField({ value, onChange, placeholder, rows=3, parent }) {
  const [recording, setRecording] = React.useState(false);
  const [supported, setSupported] = React.useState(true);
  const recRef = React.useRef(null);
  const baseRef = React.useRef("");

  React.useEffect(() => {
    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SR) { setSupported(false); return; }
  }, []);

  const start = () => {
    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SR) return;
    const rec = new SR();
    rec.continuous = true;
    rec.interimResults = true;
    rec.lang = "en-US";
    baseRef.current = value || "";
    rec.onresult = (e) => {
      let interim = "", finalT = "";
      for (let i = e.resultIndex; i < e.results.length; i++) {
        const t = e.results[i][0].transcript;
        if (e.results[i].isFinal) finalT += t;
        else interim += t;
      }
      const sep = baseRef.current && !baseRef.current.endsWith(" ") ? " " : "";
      const next = baseRef.current + sep + finalT + interim;
      onChange(next);
      if (finalT) baseRef.current = baseRef.current + sep + finalT;
    };
    rec.onerror = () => setRecording(false);
    rec.onend = () => setRecording(false);
    rec.start();
    recRef.current = rec;
    setRecording(true);
  };
  const stop = () => {
    try { recRef.current && recRef.current.stop(); } catch(e){}
    setRecording(false);
  };

  return (
    <div style={{ position:"relative" }}>
      <textarea
        rows={rows}
        value={value || ""}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
        style={{
          width:"100%",
          padding:"12px 44px 12px 14px",
          background: "var(--cream-soft)",
          border: "1px solid var(--line)",
          borderRadius: 2,
          color: "var(--ink)",
          fontSize: 13.5,
          lineHeight: 1.55,
          fontFamily:"var(--sans)",
          resize:"vertical",
          outline:"none",
        }}
        onFocus={e => e.target.style.borderColor = "var(--forest)"}
        onBlur={e => e.target.style.borderColor = "var(--line)"}
      />
      {supported && (
        <button
          onClick={recording ? stop : start}
          aria-label={recording ? "Stop dictation" : "Start dictation"}
          style={{
            position:"absolute", top:8, right:8,
            width:28, height:28, borderRadius:"50%",
            border: `1px solid ${recording ? "#9C3B2E" : "var(--line)"}`,
            background: recording ? "#9C3B2E" : "var(--cream)",
            color: recording ? "var(--cream)" : "var(--ink-2)",
            cursor:"pointer",
            display:"flex", alignItems:"center", justifyContent:"center",
            transition:"all 0.15s ease",
          }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z" fill={recording ? "currentColor" : "none"}/>
            <path d="M19 10a7 7 0 0 1-14 0M12 17v4M8 21h8"/>
          </svg>
        </button>
      )}
      {recording && (
        <div style={{
          position:"absolute", top:14, right:44,
          fontFamily:"var(--sans)", fontSize:9, fontWeight:500,
          letterSpacing:"0.16em", textTransform:"uppercase",
          color:"#9C3B2E",
        }}>● Recording</div>
      )}
    </div>
  );
}

// Slider 1–10
function Slider({ value, onChange, accent="var(--forest)" }) {
  return (
    <div style={{ display:"flex", alignItems:"center", gap:12 }}>
      <input
        type="range" min={1} max={10} step={1}
        value={value || 5}
        onChange={e => onChange(parseInt(e.target.value))}
        style={{
          flex:1,
          accentColor: accent,
        }}
      />
      <div className="serif" style={{
        flex:"0 0 32px", textAlign:"right",
        fontSize:18, fontWeight:500,
        color: accent,
      }}>{value || 5}</div>
    </div>
  );
}

// Score chip out of 10 — used for school scoring
function ScorePicker({ value, onChange, accent="var(--forest)" }) {
  return (
    <div style={{ display:"flex", gap:4, flexWrap:"wrap" }}>
      {Array.from({length:10}).map((_,i) => {
        const n = i + 1;
        const active = value === n;
        return (
          <button key={n}
            onClick={() => onChange(n)}
            style={{
              width:26, height:26,
              borderRadius:"50%",
              border:`1px solid ${active ? accent : "var(--line)"}`,
              background: active ? accent : "transparent",
              color: active ? "var(--cream)" : "var(--ink-2)",
              fontFamily:"var(--sans)", fontSize:11, fontWeight:500,
              cursor:"pointer",
              transition:"all 0.12s ease",
            }}>{n}</button>
        );
      })}
    </div>
  );
}

// Side-by-side compare: render a row with Jamie / Tom values
function CompareRow({ label, jamie, tom }) {
  const diff = (jamie != null && tom != null) ? Math.abs(jamie - tom) : null;
  const aligned = diff != null && diff <= 1;
  return (
    <div style={{
      display:"grid", gridTemplateColumns:"1fr auto auto auto",
      gap:14, alignItems:"center",
      padding:"10px 0",
      borderBottom:"1px solid var(--line-2)",
    }}>
      <div style={{ fontSize:13, color:"var(--ink-2)" }}>{label}</div>
      <div className="serif" style={{ fontSize:18, color:"var(--forest)", width:32, textAlign:"center" }}>
        {jamie != null ? jamie : "—"}
      </div>
      <div className="serif" style={{ fontSize:18, color:"var(--gold)", width:32, textAlign:"center" }}>
        {tom != null ? tom : "—"}
      </div>
      <div style={{
        width:50, textAlign:"right",
        fontFamily:"var(--sans)", fontSize:9, fontWeight:500,
        letterSpacing:"0.14em", textTransform:"uppercase",
        color: diff == null ? "var(--ink-3)" : aligned ? "var(--moss)" : "#9C3B2E",
      }}>
        {diff == null ? "—" : aligned ? "Aligned" : `Δ ${diff}`}
      </div>
    </div>
  );
}

Object.assign(window, { PARENTS, VoiceField, Slider, ScorePicker, CompareRow });
