// AI Builder — prompt → streaming reasoning → generated journey

const StreamingLine = ({ children, delay = 0, mono = false }) => (
  <div style={{
    fontSize: 13, color: "var(--mw-text-secondary)",
    fontFamily: mono ? "var(--mw-font-mono)" : "inherit",
    animation: `mw-row-in 240ms ${delay}ms var(--mw-ease) both`,
    display: "flex", alignItems: "center", gap: 8,
  }}>
    <span style={{
      width: 6, height: 6, borderRadius: "50%",
      background: "var(--mw-brand-500)", flexShrink: 0,
      animation: "mw-orb-breathe 1.6s ease-in-out infinite",
    }} />
    <span>{children}</span>
  </div>
);

const BuiltRow = ({ label, value, delay = 0, kind = "step", icon }) => {
  const palette = {
    step: { bg: "#fff", border: "var(--mw-border)", labelFg: "var(--mw-brand-500)" },
    skip: { bg: "rgba(255, 249, 224, 0.5)", border: "rgba(178,121,26,.25)", labelFg: "var(--mw-warning)" },
    exit: { bg: "rgba(218, 240, 224, 0.4)", border: "rgba(34,134,58,.25)", labelFg: "var(--mw-success)" },
    trig: { bg: "#1A1B25", border: "#1A1B25", labelFg: "rgba(255,255,255,.65)", valueFg: "#fff" },
  }[kind];
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 12, padding: "10px 14px",
      background: palette.bg, border: `1px solid ${palette.border}`, borderRadius: 10,
      animation: `mw-row-in 320ms ${delay}ms var(--mw-ease) both`,
    }}>
      {icon}
      <span style={{ fontSize: 11, fontWeight: 600, color: palette.labelFg, textTransform: "uppercase", letterSpacing: 0.4, minWidth: 76 }}>
        {label}
      </span>
      <span style={{ fontSize: 13, color: palette.valueFg || "var(--mw-text-primary)", flex: 1 }}>
        {value}
      </span>
    </div>
  );
};

const AIBuilderPage = ({ onCancel, onActivate, streamSpeed = "fast", examplePromptIdx = 0 }) => {
  const [prompt, setPrompt] = React.useState(EXAMPLE_PROMPTS[examplePromptIdx] || STREAM_SCRIPT.prompt);
  const [stage, setStage] = React.useState("idle"); // idle | streaming | ready
  const [revealed, setRevealed] = React.useState(0);

  // Sync prompt when example changes from tweaks
  React.useEffect(() => {
    if (stage === "idle") setPrompt(EXAMPLE_PROMPTS[examplePromptIdx] || STREAM_SCRIPT.prompt);
  }, [examplePromptIdx]);

  const speedMs = streamSpeed === "instant" ? 0 : streamSpeed === "dramatic" ? 380 : 140;
  const totalSteps = STREAM_SCRIPT.reasoning.length;

  const start = React.useCallback(() => {
    setStage("streaming");
    setRevealed(0);
    if (streamSpeed === "instant") {
      setRevealed(totalSteps);
      setStage("ready");
      return;
    }
    let i = 0;
    const tick = () => {
      i++;
      setRevealed(i);
      if (i < totalSteps) {
        setTimeout(tick, speedMs);
      } else {
        setStage("ready");
      }
    };
    setTimeout(tick, speedMs);
  }, [streamSpeed]);

  const reset = () => { setStage("idle"); setRevealed(0); };

  const visible = STREAM_SCRIPT.reasoning.slice(0, revealed);
  const thinks = visible.filter((s) => s.kind === "think");
  const builds = visible.filter((s) => s.kind === "build");
  const doneMsg = visible.find((s) => s.kind === "done");

  const buildByKey = (k) => builds.find((b) => b.key === k);

  return (
    <div data-screen-label="02 AI Builder" style={{ padding: "24px 28px", maxWidth: 1320, margin: "0 auto" }}>
      {/* Title */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--mw-text-tertiary)", fontSize: 12, marginBottom: 4 }}>
            <span onClick={onCancel} style={{ cursor: "pointer" }}>Templates</span>
            <Icon name="chevronRight" size={12} opacity={0.5} />
            <span>New Template</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <AIOrb size={26} spin={stage === "streaming"} />
            <h1 className="mw-h1" style={{ fontSize: 26 }}>
              Build a template <span style={{ color: "var(--mw-text-tertiary)", fontWeight: 500 }}>with AI</span>
            </h1>
          </div>
          <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", marginTop: 6 }}>
            Defines a reusable automation. Many quotes, leads, or customers can run on this template over time.
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <Button onClick={onCancel}>Cancel</Button>
          {stage === "ready" ? (
            <Button kind="primary" icon="check" onClick={() => onActivate("midflight")}>Publish Template</Button>
          ) : (
            <Button kind="primary" disabled>Publish Template</Button>
          )}
        </div>
      </div>

      {/* Two-column layout */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(420px, 1fr) 1.4fr", gap: 20 }}>
        {/* LEFT — Prompt + reasoning */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>

          {/* Prompt card — glossy AI gradient frame */}
          <div style={{
            position: "relative", padding: 2, borderRadius: 18,
            background: "linear-gradient(135deg, #7BC8FF, #534aff 50%, #7B3DCC)",
            boxShadow: "0 8px 28px -12px rgba(83,74,255,.45)",
          }}>
            <div style={{ background: "#fff", borderRadius: 16, padding: 18 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
                <AIOrb size={20} />
                <span style={{ fontSize: 13, fontWeight: 600 }}>Describe your template</span>
                <span style={{ fontSize: 12, color: "var(--mw-text-tertiary)", marginLeft: "auto" }}>
                  Trigger · Timeline · Conditions · Exit rules
                </span>
              </div>
              <textarea
                value={prompt}
                onChange={(e) => setPrompt(e.target.value)}
                disabled={stage !== "idle"}
                placeholder="e.g. Create a quote follow-up journey with check-ins at 7, 21, 60, and 90 days unless communication is already happening."
                style={{
                  width: "100%", minHeight: 96, resize: "vertical",
                  border: "1px solid var(--mw-border)", borderRadius: 10, padding: 12,
                  fontSize: 14, lineHeight: 1.5, color: "var(--mw-text-primary)",
                  background: stage === "idle" ? "#fff" : "var(--mw-bg)",
                }}
              />
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 12 }}>
                <div style={{ display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap" }}>
                  <span style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>Examples:</span>
                  {EXAMPLE_PROMPTS.slice(0, 3).map((p, i) => (
                    <button key={i}
                      onClick={() => setPrompt(p)}
                      disabled={stage !== "idle"}
                      style={{
                        fontSize: 11, padding: "3px 8px", borderRadius: 9999,
                        border: "1px solid var(--mw-border)", background: "#fff", cursor: "pointer",
                        color: "var(--mw-text-secondary)", maxWidth: 200, overflow: "hidden",
                        textOverflow: "ellipsis", whiteSpace: "nowrap",
                      }}>
                      {p.slice(0, 36)}…
                    </button>
                  ))}
                </div>
                {stage === "idle" && (
                  <Button kind="ai" icon="ai" onClick={start}>Generate</Button>
                )}
                {stage === "streaming" && (
                  <span style={{ fontSize: 12, color: "var(--mw-brand-500)", display: "inline-flex", alignItems: "center", gap: 6 }}>
                    <AIOrb size={14} spin /> <span className="mw-ai-text-grad" style={{ fontWeight: 600 }}>Thinking…</span>
                  </span>
                )}
                {stage === "ready" && (
                  <Button onClick={reset} icon="cross">Start over</Button>
                )}
              </div>
            </div>
          </div>

          {/* Thinking trace */}
          {stage !== "idle" && (
            <div className="mw-card" style={{ padding: 16 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
                <Icon name="layers" size={14} opacity={0.7} />
                <span style={{ fontSize: 13, fontWeight: 600 }}>Reasoning trace</span>
                <span style={{ fontSize: 11, color: "var(--mw-text-tertiary)", marginLeft: "auto" }}>
                  {thinks.length} step{thinks.length === 1 ? "" : "s"}
                </span>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {thinks.map((t, i) => (
                  <StreamingLine key={i} delay={i * 40}>{t.text}</StreamingLine>
                ))}
                {stage === "streaming" && thinks.length > 0 && (
                  <div style={{ fontSize: 13, color: "var(--mw-text-tertiary)", marginLeft: 14 }}>
                    <span className="mw-stream-cursor" />
                  </div>
                )}
                {doneMsg && (
                  <div style={{ marginTop: 4, padding: 10, borderRadius: 8, background: "var(--mw-success-bg)",
                    color: "var(--mw-success)", fontSize: 13, fontWeight: 500, display: "flex", alignItems: "center", gap: 8 }}>
                    <Icon name="check" size={14} />
                    {doneMsg.text}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>

        {/* RIGHT — generated journey appearing piece by piece */}
        <div className="mw-card" style={{ padding: 20, minHeight: 480, display: "flex", flexDirection: "column" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
            <span style={{ fontSize: 13, fontWeight: 600 }}>Generated Journey</span>
            <span style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>· preview</span>
            <span style={{ flex: 1 }} />
            {stage === "ready" && <Chip tone="success" dot>Ready</Chip>}
            {stage === "streaming" && <Chip tone="info" dot>Building</Chip>}
            {stage === "idle" && <Chip tone="neutral">Draft</Chip>}
          </div>
          <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", marginBottom: 14 }}>
            New: <span style={{ color: "var(--mw-text-primary)", fontWeight: 500 }}>Quote Follow-Up Template</span>
          </div>

          {stage === "idle" ? (
            <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
              gap: 12, color: "var(--mw-text-tertiary)" }}>
              <div style={{ width: 96, height: 96, borderRadius: "50%", position: "relative" }}>
                <div style={{ position: "absolute", inset: 0, borderRadius: "50%",
                  background: "radial-gradient(circle at 30% 30%, rgba(123,200,255,.35), rgba(83,74,255,.05) 70%)" }} />
                <div style={{ position: "absolute", inset: 16, borderRadius: "50%", border: "1.5px dashed rgba(83,74,255,.35)" }} />
                <div style={{ position: "absolute", left: "50%", top: "50%", transform: "translate(-50%,-50%)" }}>
                  <AIOrb size={32} />
                </div>
              </div>
              <span style={{ fontSize: 13 }}>Your generated journey will appear here.</span>
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {buildByKey("trigger") && (
                <BuiltRow label="Trigger" kind="trig" delay={0}
                  icon={<StepIcon kind="trigger" status="done" size={24} />}
                  value={buildByKey("trigger").value} />
              )}
              {["step1","step2","step3","step4"].map((k, i) => {
                const b = buildByKey(k);
                if (!b) return null;
                const isTask = k === "step3";
                return (
                  <BuiltRow key={k} label={b.label} kind="step" delay={i * 60}
                    icon={<StepIcon kind={isTask ? "task" : "email"} status="pending" size={24} />}
                    value={b.value} />
                );
              })}
              {["skip1","skip2"].map((k, i) => {
                const b = buildByKey(k);
                if (!b) return null;
                return (
                  <BuiltRow key={k} label={b.label} kind="skip" delay={i * 50}
                    icon={<Icon name="branch" size={18} style={{ opacity: 0.7 }} />}
                    value={b.value} />
                );
              })}
              {["exit1","exit2"].map((k, i) => {
                const b = buildByKey(k);
                if (!b) return null;
                return (
                  <BuiltRow key={k} label={b.label} kind="exit" delay={i * 50}
                    icon={<Icon name="check" size={18} />}
                    value={b.value} />
                );
              })}

              {stage === "ready" && (
                <div style={{ marginTop: 10, padding: 12, borderRadius: 10, background: "var(--mw-bg)",
                  display: "flex", alignItems: "center", gap: 10, animation: "mw-row-in 320ms var(--mw-ease) both" }}>
                  <Icon name="infoCircle" size={14} opacity={0.7} />
                  <span style={{ fontSize: 12, color: "var(--mw-text-secondary)" }}>
                    Publishing will enroll <strong>new Quote Sent</strong> events. Existing in-flight journeys won't be touched.
                  </span>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { AIBuilderPage });
