/* planner-smart-add.jsx — paste-a-note modal that proposes lessons via Cloudflare Workers AI */

function PlannerSmartAdd({ open, settings, currentWeekStart, onClose, onAdd }) {
  const { BLOCK_TYPES, PALETTE, DAY_SHORT, fmtTime, fmtDur } = window.PLANNER_DATA;
  const [text, setText] = React.useState("");
  const [phase, setPhase] = React.useState("idle"); // idle | loading | preview | error
  const [proposed, setProposed] = React.useState([]);
  const [warnings, setWarnings] = React.useState([]);
  const [errorMsg, setErrorMsg] = React.useState("");
  const textareaRef = React.useRef(null);

  React.useEffect(() => {
    if (open) {
      setPhase("idle");
      setProposed([]);
      setWarnings([]);
      setErrorMsg("");
      const id = requestAnimationFrame(() => {
        if (textareaRef.current) textareaRef.current.focus();
      });
      return () => cancelAnimationFrame(id);
    }
  }, [open]);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onClose();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  const analyze = async () => {
    const trimmed = text.trim();
    if (!trimmed) {
      setErrorMsg("Paste your week's notes first.");
      setPhase("error");
      return;
    }
    setPhase("loading");
    setErrorMsg("");
    try {
      const res = await fetch("/api/smart-add", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          text: trimmed,
          settings,
          weekStart: currentWeekStart
        })
      });
      const payload = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(payload.error || "Could not generate a plan.");
      const lessons = Array.isArray(payload.lessons) ? payload.lessons : [];
      if (!lessons.length) {
        setErrorMsg("I couldn't find any lessons in that note — try adding clearer days and times.");
        setPhase("error");
        return;
      }
      const palette = PALETTE;
      const enriched = lessons.map((l, i) => ({
        ...l,
        color: palette[i % palette.length],
        include: true,
        localId: "sa-" + i
      }));
      setProposed(enriched);
      setWarnings(Array.isArray(payload.warnings) ? payload.warnings : []);
      setPhase("preview");
    } catch (err) {
      setErrorMsg(err.message || "Smart add failed.");
      setPhase("error");
    }
  };

  const toggleInclude = (id) => {
    setProposed(items => items.map(it => it.localId === id ? { ...it, include: !it.include } : it));
  };

  const updateProposed = (id, patch) => {
    setProposed(items => items.map(it => it.localId === id ? { ...it, ...patch } : it));
  };

  const addSelected = () => {
    const picked = proposed.filter(p => p.include).map(({ include, localId, ...rest }) => rest);
    onAdd(picked);
  };

  const selectedCount = proposed.filter(p => p.include).length;

  return (
    <>
      <div className="smart-backdrop" onClick={onClose}/>
      <div className="smart-modal" role="dialog" aria-label="Smart add lessons">
        <button className="close-btn" onClick={onClose} title="Close"><window.Icon.close/></button>
        <p className="e-eyebrow">Smart add</p>
        <h2 style={{display:"flex", alignItems:"center", gap:10}}>
          <span style={{color:"var(--c-fri)"}}><window.Icon.sparkle/></span>
          Paste your week
        </h2>
        <p className="smart-help">
          Plain notes work — bullet points, schedules, even messy text. Powered by Cloudflare Workers AI.
        </p>

        {phase !== "preview" && (
          <>
            <textarea
              ref={textareaRef}
              className="smart-textarea"
              value={text}
              onChange={(e) => setText(e.target.value)}
              placeholder={"Example:\n• Monday math 9–10\n• Tuesday reading workshop 10:15–11\n• Wed art with afternoon class 1pm for 45 min\n• Friday PE outside 1:30\n• Every weekday morning circle 8:30 for 20 min"}
              rows={10}
              maxLength={4000}
              disabled={phase === "loading"}
            />
            {phase === "error" && errorMsg && <div className="smart-error">{errorMsg}</div>}
            <div className="smart-actions">
              <button
                type="button"
                className="btn-secondary"
                onClick={onClose}
                disabled={phase === "loading"}
              >
                Cancel
              </button>
              <button
                type="button"
                className="btn-primary"
                onClick={analyze}
                disabled={phase === "loading" || !text.trim()}
              >
                {phase === "loading" ? "Thinking…" : <><window.Icon.sparkle/> Generate plan</>}
              </button>
            </div>
          </>
        )}

        {phase === "preview" && (
          <>
            <p className="smart-summary">
              Found {proposed.length} lesson{proposed.length === 1 ? "" : "s"} — uncheck anything you don't want.
            </p>
            {warnings.length > 0 && (
              <ul className="smart-warnings">
                {warnings.map((w, i) => <li key={i}>⚠️ {w}</li>)}
              </ul>
            )}
            <div className="smart-list">
              {proposed.map(p => (
                <SmartRow
                  key={p.localId}
                  item={p}
                  onToggle={() => toggleInclude(p.localId)}
                  onChange={(patch) => updateProposed(p.localId, patch)}
                  blockTypes={BLOCK_TYPES}
                  dayShort={DAY_SHORT}
                  fmtTime={fmtTime}
                  fmtDur={fmtDur}
                  dayCount={settings.includeWeekend ? 7 : 5}
                />
              ))}
            </div>
            <div className="smart-actions">
              <button type="button" className="btn-secondary" onClick={() => setPhase("idle")}>
                Start over
              </button>
              <button
                type="button"
                className="btn-primary"
                onClick={addSelected}
                disabled={!selectedCount}
              >
                <window.Icon.check/> Add {selectedCount || ""} lesson{selectedCount === 1 ? "" : "s"}
              </button>
            </div>
          </>
        )}
      </div>
    </>
  );
}

function SmartRow({ item, onToggle, onChange, blockTypes, dayShort, fmtTime, fmtDur, dayCount }) {
  const typeMeta = blockTypes.find(t => t.id === item.typeId) || blockTypes[0];
  const TypeIcon = (window.Icon[typeMeta.icon]) || window.Icon.book;
  const isRepeating = Array.isArray(item.repeatDays) && item.repeatDays.length > 1;
  return (
    <label className={"smart-row" + (item.include ? " on" : " off")}>
      <input
        type="checkbox"
        checked={item.include}
        onChange={onToggle}
      />
      <span className="smart-row-color" style={{ background: item.color }}/>
      <div className="smart-row-body">
        <input
          type="text"
          className="smart-row-title"
          value={item.title}
          maxLength={80}
          onChange={(e) => onChange({ title: e.target.value })}
          onClick={(e) => e.stopPropagation()}
        />
        <div className="smart-row-meta">
          <span className="smart-row-icon"><TypeIcon/></span>
          <select
            value={item.dayIndex}
            onChange={(e) => onChange({ dayIndex: Number(e.target.value) })}
            onClick={(e) => e.stopPropagation()}
          >
            {dayShort.slice(0, dayCount).map((n, i) => <option key={i} value={i}>{n}</option>)}
          </select>
          <span className="smart-row-time">
            {fmtTime(item.start)} – {fmtTime(item.end)}
          </span>
          <span className="smart-row-dur">{fmtDur(item.end - item.start)}</span>
          {isRepeating && (
            <span className="smart-row-repeat">
              repeats {item.repeatDays.map(d => dayShort[d]).join(", ")}
            </span>
          )}
        </div>
      </div>
    </label>
  );
}

window.PlannerSmartAdd = PlannerSmartAdd;
