/* eslint-disable */
// ===========================================================================
// Omnivore UI — Add / Scan sheet (camera + clarify + result)
//
// Part of the in-browser (no-build) React app. These files are loaded in order
// as separate <script type="text/babel"> tags (see index.html); Babel compiles
// each as a classic global script, so top-level names declared in earlier files
// are visible here. Depends on ui/base.jsx, ui/components.jsx.
// ===========================================================================

// ── clarify questions (paper theme) ──────────────────────────────────────────
function Clarify({ questions, onSubmit }) {
  const [chosen, setChosen] = useState(() => questions.map(() => null));
  const [typed, setTyped] = useState(() => questions.map(() => ""));
  const ready = chosen.every((c, i) => c != null || typed[i].trim());
  function pick(qi, opt) { setChosen((c) => c.map((v, i) => (i === qi ? opt : v))); setTyped((t) => t.map((v, i) => (i === qi ? "" : v))); }
  function type(qi, val) { setTyped((t) => t.map((v, i) => (i === qi ? val : v))); if (val.trim()) setChosen((c) => c.map((v, i) => (i === qi ? null : v))); }
  function submit() {
    onSubmit(questions.map((q, i) => ({ question: q.question, answer: typed[i].trim() || chosen[i] || (q.options && q.options[0]) || "" })));
  }
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <p style={{ fontSize: 14, color: C.text, fontWeight: 600, margin: 0 }}>A couple of quick questions to get this right:</p>
      {questions.map((q, qi) => (
        <div key={qi} style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <p style={{ fontSize: 14, color: C.text, margin: 0 }}>{q.question}</p>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {(q.options || []).map((opt) => (
              <button key={opt} onClick={() => pick(qi, opt)} style={pillBtn(chosen[qi] === opt)}>{opt}</button>
            ))}
          </div>
          <input type="text" value={typed[qi]} onChange={(e) => type(qi, e.target.value)} placeholder="Or type your own…"
            style={{ ...inputStyle, padding: "9px 12px", fontSize: 14 }} />
        </div>
      ))}
      <button onClick={submit} disabled={!ready}
        style={{ ...pillBtn(true), padding: "11px 0", borderRadius: 12, opacity: ready ? 1 : 0.4 }}>Continue</button>
    </div>
  );
}

// ── result (paper theme) ─────────────────────────────────────────────────────
function Result({ entry, onLog, onDiscard }) {
  const [eatenAt, setEatenAt] = useState(nowForInput);
  const N = entry.nutrients || {};
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div>
        <h3 style={{ fontSize: 18, fontWeight: 600, color: C.text, margin: 0, fontFamily: SERIF }}>{entry.description || "Food entry"}</h3>
        <span style={{ fontSize: 12, color: C.dim }}>{entry.confidence} confidence</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, textAlign: "center" }}>
        {[["calories", "kcal"], ["protein", "protein"], ["carbs", "carbs"], ["fat", "fat"]].map(([k, label]) => {
          const n = N[k] || {};
          return (
            <div key={k} style={{ background: C.card, borderRadius: 12, padding: "10px 0" }}>
              <div style={{ fontSize: 18, fontWeight: 600, color: C.text }}>{n.known ? fmt(n.amount) : "—"}</div>
              <div style={{ fontSize: 11, color: C.faint }}>{label}</div>
            </div>
          );
        })}
      </div>
      <MealDetail meal={entry} />
      <div>
        <label style={{ fontSize: 12, color: C.faint, marginBottom: 5, display: "block" }}>When did you eat this?</label>
        <input type="datetime-local" value={eatenAt} onChange={(e) => setEatenAt(e.target.value)} style={{ ...inputStyle, width: "auto" }} />
      </div>
      <div style={{ display: "flex", gap: 8 }}>
        <button onClick={() => onLog(entry, eatenAt ? eatenAt + ":00" : null)}
          style={{ ...pillBtn(true), flex: 1, padding: "12px 0", borderRadius: 12 }}>Log it</button>
        <button onClick={onDiscard} style={{ ...pillBtn(false), flex: 1, padding: "12px 0", borderRadius: 12 }}>Discard</button>
      </div>
    </div>
  );
}

// ── ADD / SCAN sheet (live camera + text; analyze → clarify → result) ────────
function AddSheet({ focused, setFocused, captured, setCaptured, text, setText,
                    status, questions, result, error, busy, onAnswer, onLog, onDiscard, onClose }) {
  const videoRef = useRef(null);
  const streamRef = useRef(null);
  const [camErr, setCamErr] = useState(null);
  const liveCamera = status === "capture" && !captured;

  // start/stop the camera with the live-preview state
  useEffect(() => {
    let cancelled = false;
    async function start() {
      if (!liveCamera) return;
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { setCamErr("Camera not available on this device."); return; }
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: "environment" } }, audio: false });
        if (cancelled) { stream.getTracks().forEach((t) => t.stop()); return; }
        streamRef.current = stream;
        if (videoRef.current) { videoRef.current.srcObject = stream; videoRef.current.play().catch(() => {}); }
        setCamErr(null);
      } catch (e) {
        setCamErr("Camera blocked — describe your meal below instead.");
      }
    }
    start();
    return () => {
      cancelled = true;
      if (streamRef.current) { streamRef.current.getTracks().forEach((t) => t.stop()); streamRef.current = null; }
    };
  }, [liveCamera]);

  function capture() {
    const v = videoRef.current;
    if (!v || !v.videoWidth) return;
    const cn = document.createElement("canvas");
    cn.width = v.videoWidth; cn.height = v.videoHeight;
    cn.getContext("2d").drawImage(v, 0, 0, cn.width, cn.height);
    setCaptured(cn.toDataURL("image/jpeg", 0.9));
  }

  const showCapture = status === "capture";
  const analyzing = status === "analyzing";
  const drag = useDragToClose(onClose);

  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 35, display: "flex", flexDirection: "column", background: "rgba(15,16,18,0.55)" }}>
      <div onClick={onClose} style={{ flex: focused ? 0 : "0 0 12px", minHeight: 12 }} />
      <div style={{ flex: 1, background: C.bg, borderRadius: "20px 20px 0 0", display: "flex", flexDirection: "column",
        padding: showCapture ? "14px 18px 96px" : "14px 18px 28px", gap: 14, overflowY: showCapture ? "hidden" : "auto",
        ...drag.style }}>
        {/* grab handle — drag down to dismiss */}
        <div {...drag.handlers} style={{ flexShrink: 0, padding: "2px 0 6px", margin: "-2px 0 -4px", touchAction: "none", cursor: "grab" }}>
          <div style={{ width: 36, height: 4, background: C.line, borderRadius: 2, margin: "0 auto" }} />
        </div>

        {showCapture && (
          <>
            {/* camera / captured preview — shrinks when keyboard is up; drag to dismiss */}
            <div {...drag.handlers} style={{ flex: focused ? "0 0 84px" : 1, minHeight: 84, transition: "flex-basis .25s",
              background: "#000", borderRadius: 14, overflow: "hidden", position: "relative", touchAction: "none",
              display: "flex", alignItems: "center", justifyContent: "center" }}>
              {captured ? (
                <img src={captured} alt="Meal" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              ) : (
                <>
                  <video ref={videoRef} muted playsInline autoPlay
                    style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                  {camErr && (
                    <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center",
                      textAlign: "center", color: C.faint, fontSize: 13, padding: 20 }}>{camErr}</div>
                  )}
                  {!camErr && (
                    <div style={{ position: "absolute", width: 54, height: 54, border: "2px solid rgba(255,255,255,0.5)", borderRadius: 8 }} />
                  )}
                </>
              )}
              {/* shutter / retake — hidden when keyboard up to save room */}
              {!focused && (
                captured ? (
                  <button onClick={() => setCaptured(null)}
                    style={{ position: "absolute", bottom: 12, left: "50%", transform: "translateX(-50%)",
                      background: "rgba(0,0,0,0.55)", color: "#fff", border: "1px solid rgba(255,255,255,0.5)",
                      borderRadius: 18, padding: "7px 16px", fontSize: 13, cursor: "pointer" }}>↻ Retake</button>
                ) : !camErr ? (
                  <button onClick={capture}
                    style={{ position: "absolute", bottom: 14, left: "50%", transform: "translateX(-50%)",
                      width: 56, height: 56, borderRadius: "50%", background: "rgba(255,255,255,0.15)",
                      border: "3px solid #fff", cursor: "pointer", padding: 0,
                      display: "flex", alignItems: "center", justifyContent: "center" }}>
                    <span style={{ width: 42, height: 42, borderRadius: "50%", background: "#fff", display: "block" }} />
                  </button>
                ) : null
              )}
            </div>

            {/* description field */}
            <textarea value={text} onChange={(e) => setText(e.target.value)}
              onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
              placeholder="…or describe the meal"
              style={{ flex: "0 0 auto", height: 56, background: C.card, border: `1px solid ${C.line}`,
                borderRadius: 12, color: C.text, padding: 12, fontSize: 15, resize: "none", boxSizing: "border-box" }} />

            {error && <div style={{ fontSize: 13, color: C.over, flexShrink: 0 }}>{error}</div>}
          </>
        )}

        {analyzing && (
          <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "30px 4px", color: C.dim, fontSize: 14 }}>
            <span style={{ width: 16, height: 16, border: `2px solid ${C.line}`, borderTopColor: C.accent,
              borderRadius: "50%", display: "inline-block", animation: "omspin 0.8s linear infinite" }} />
            <span>Analyzing… this can take a few seconds.</span>
            <style>{`@keyframes omspin{to{transform:rotate(360deg)}}`}</style>
          </div>
        )}

        {status === "clarify" && questions && <Clarify questions={questions} onSubmit={onAnswer} />}
        {status === "result" && result && <Result entry={result} onLog={onLog} onDiscard={onDiscard} />}
      </div>
    </div>
  );
}
