// Spec Builder — AI Conversation. `bare` skips its own TopBar so it can be
// embedded inside another shell (used by /settings Automation tab). In bare
// mode, the parent shell drives the right-side inset via the `viewTab` prop:
// null = chat only, "preview" = spec preview shown right of chat,
// "file" = instruction file shown right of chat. Layout: angel (decorative,
// floating) on the left, narrow chat pillow center, optional inset panel right.
const SpecBuilder = ({ width = 1440, height = 980, bare = false, viewTab = null, onCloseView }) => {
  const connected = (typeof useConnected === "function") ? useConnected() : null;

  // Demo mode: show the full pre-baked conversation so reviewers can read
  // through what the chat is supposed to feel like. Logged-in mode: just the
  // opening prompt — the rest will fill in once we wire the chat to the API.
  const fullMessages = [
    { from: "ai", text: "Let's set up your inbox. To start — for emails from clients about account access, what should I do? I'll learn from your answer." },
    { from: "user", text: "Always send those to me. They're often urgent and I want eyes on them." },
    { from: "ai", text: "Got it — Human Required for account access. What about routine confirmations from operations (settlement, statements)?" },
    { from: "user", text: "Auto-reply with a thank-you and route to my Ops folder. No need to bother me." },
    { from: "ai", text: "Done. One last on this round: complaints. Should I draft a response for review or escalate to your compliance team directly?" },
  ];
  const fullChips = ["Draft for me to review", "Escalate to compliance", "Both — draft AND notify compliance"];

  const messages = connected ? fullMessages.slice(0, 1) : fullMessages;
  const chips = connected ? [] : fullChips;

  if (bare) {
    // Symmetric layout: an angel on each side, chat + inset centered between
    // them. Left angel faces right (view="side"), right angel faces left
    // (view="front"). They sit at offset vertical heights — left a touch
    // higher, right a touch lower — to feel like a hovering pair rather
    // than a mirrored reflection.
    const ANGEL_BOX = 120;
    return (
      <div style={{
        width: "100%", height: "100%",
        display: "flex", alignItems: "center", justifyContent: "center",
        gap: 32, padding: "0 32px",
        minHeight: 0, overflow: "hidden",
      }}>
        <div style={{
          flexShrink: 0,
          marginTop: -56,
          animation: "rg-float-soft 2.8s ease-in-out infinite",
        }}>
          <AngelRobot size={ANGEL_BOX} view="side"/>
        </div>

        <ConvoColumn messages={messages} chips={chips} bare/>

        {viewTab && <SpecInset viewTab={viewTab}/>}

        <div style={{
          flexShrink: 0,
          marginTop: 56,
          animation: "rg-float-soft 2.8s ease-in-out infinite 0.9s",
        }}>
          <AngelRobot size={ANGEL_BOX} view="front"/>
        </div>
      </div>
    );
  }

  const wrapperStyle = { width, height, background: "var(--white-pure)", display: "flex", flexDirection: "column" };

  // Non-bare (legacy /spec route): two-column with side preview baked in
  return (
    <div style={wrapperStyle}>
      <TopBar active="Settings"/>

      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "1fr 420px", gap: 32, padding: "32px 64px", minHeight: 0 }}>
        <div style={{ display: "flex", flexDirection: "column", maxWidth: 760, width: "100%", justifySelf: "center", minHeight: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 8 }}>
            <AngelRobot size={56} facing="right"/>
            <div>
              <div className="h2">Tell RedGone what emails it can answer.</div>
              <div className="small" style={{ color: "var(--midnight-soft)", marginTop: 4 }}>
                A short conversation. The spec on the right updates as we go.
              </div>
            </div>
          </div>
          <ConvoColumn messages={messages} chips={chips}/>
        </div>
        <div className="pillow float-in" style={{ padding: 24, alignSelf: "stretch", display: "flex", flexDirection: "column", minHeight: 0 }}>
          <SpecPreview/>
        </div>
      </div>
    </div>
  );
};

const ConvoColumn = ({ messages, chips, bare }) => {
  // Compact, fixed-size cloud pillow in bare mode (mirrors the compose
  // card's vibe — narrower and a bit shorter). Non-bare keeps the earlier
  // transparent layout for the standalone /spec route.
  if (bare) {
    return (
      <div className="pillow" style={{
        display: "flex", flexDirection: "column",
        width: 460, height: 540,
        flexShrink: 0,
        padding: 20,
      }}>
        <div className="scroll" style={{
          flex: 1, overflow: "auto", paddingRight: 4,
          display: "flex", flexDirection: "column", gap: 8,
          minHeight: 0,
        }}>
          {messages.map((m, i) => (
            <div key={i} style={{ display: "flex", justifyContent: m.from === "user" ? "flex-end" : "flex-start" }}>
              <div style={{
                padding: "9px 13px", borderRadius: 14, maxWidth: 520,
                background: m.from === "user" ? "var(--midnight)" : "var(--white-soft)",
                color: m.from === "user" ? "#FFFFFF" : "var(--midnight)",
                fontSize: 13.5, lineHeight: 1.45,
              }}>
                {m.from === "ai" && (
                  <div className="micro" style={{
                    color: "var(--midnight-soft)", marginBottom: 3,
                    fontSize: 10,
                  }}>RedGone</div>
                )}
                {m.text}
              </div>
            </div>
          ))}
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 2 }}>
            {chips.map(c => (
              <div key={c} className="neu-chip" style={{ padding: "6px 12px", fontSize: 12 }}>{c}</div>
            ))}
          </div>
        </div>

        <div style={{
          marginTop: 10,
          display: "flex", alignItems: "center", gap: 8,
          flexShrink: 0,
        }}>
          <input className="neu-input" placeholder="Reply to RedGone…"
                 style={{ flex: 1, padding: "10px 14px", fontSize: 13.5 }}/>
          <button className="neu-btn-redglow neu-btn-redglow-sm">
            <span>Send</span>
            <span style={{ opacity: 0.7 }}>→</span>
          </button>
        </div>
      </div>
    );
  }

  // Non-bare (legacy /spec route) — original transparent layout
  return (
    <div style={{
      display: "flex", flexDirection: "column",
      width: "100%", maxWidth: 760,
      margin: "0 auto",
      flex: 1, minHeight: 0,
    }}>
      <div className="scroll" style={{
        flex: 1, overflow: "auto", paddingRight: 8,
        display: "flex", flexDirection: "column", gap: 14,
        minHeight: 0,
      }}>
        {messages.map((m, i) => (
          <div key={i} style={{ display: "flex", justifyContent: m.from === "user" ? "flex-end" : "flex-start" }}>
            <div className={m.from === "ai" ? "pillow" : ""} style={{
              padding: "14px 18px", borderRadius: 18, maxWidth: 520,
              background: m.from === "user" ? "var(--midnight)" : "#FFFFFF",
              color: m.from === "user" ? "#FFFFFF" : "var(--midnight)",
              boxShadow: m.from === "user" ? "0 8px 24px rgba(10,22,40,0.18)" : undefined,
              border: m.from === "user" ? "none" : undefined,
              fontSize: 14.5, lineHeight: 1.55,
            }}>
              {m.from === "ai" && (
                <div className="micro" style={{ color: "var(--midnight-soft)", marginBottom: 6 }}>RedGone</div>
              )}
              {m.text}
            </div>
          </div>
        ))}
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 4, marginLeft: 4 }}>
          {chips.map(c => (<div key={c} className="neu-chip">{c}</div>))}
        </div>
      </div>
      <div style={{ marginTop: 14, display: "flex", alignItems: "center", gap: 10, flexShrink: 0 }}>
        <input className="neu-input" placeholder="Reply to RedGone…"
               style={{ flex: 1, padding: "13px 16px", fontSize: 14 }}/>
        <button className="neu-btn-redglow" style={{ padding: "11px 18px" }}>
          <span>Send</span>
          <span style={{ opacity: 0.7 }}>→</span>
        </button>
      </div>
    </div>
  );
};

// Inset content panel — sits to the right of the chat in bare mode. Styled
// as a recessed "hole" against the white page background (neu-in shadow on
// var(--white-soft)), matching the same surface used by the textareas
// elsewhere. Same fixed dimensions as the chat pillow for visual symmetry.
const SpecInset = ({ viewTab }) => (
  <div className="scroll float-in" style={{
    width: 460, height: 540,
    flexShrink: 0,
    background: "var(--white-soft)",
    boxShadow: "var(--neu-in)",
    borderRadius: 20,
    padding: 22,
    overflow: "auto",
    display: "flex", flexDirection: "column",
  }}>
    {viewTab === "preview" ? <SpecPreview/> : <InstructionFileEditor/>}
  </div>
);

const SPEC_RULES = [
  { cat: "Human Required",  rules: ["Account access requests", "Anything tagged 'COMPLAINT'", "First-time clients (< 90 days)"] },
  { cat: "AI Drafts",       rules: ["Portfolio reviews and updates", "Pricing or quote requests", "Internal sign-off threads"] },
  { cat: "Auto-Reply OK",   rules: ["Settlement confirmations from Ops", "Read-receipts and meeting acks", "Newsletter / regulatory feeds"] },
  { cat: "Human Sends",     rules: ["RFPs from prospects", "Press / media inquiries"] },
];

const SpecPreview = () => (
  <>
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
      <div className="micro">Spec preview · live</div>
      <span className="mono" style={{ fontSize: 11, color: "var(--success-mint)" }}>● UPDATING</span>
    </div>
    <div className="h3" style={{ marginTop: 8 }}>Your inbox rules</div>
    <div className="scroll" style={{ marginTop: 16, overflow: "auto", display: "flex", flexDirection: "column", gap: 16, flex: 1 }}>
      {SPEC_RULES.map(g => (
        <div key={g.cat}>
          <div className="micro" style={{ color: "var(--midnight)", marginBottom: 8 }}>{g.cat}</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {g.rules.map(r => (
              <div key={r} style={{
                padding: "10px 12px", borderRadius: 10,
                background: "var(--white-soft)", fontSize: 13, color: "var(--midnight)",
                display: "flex", alignItems: "center", gap: 8,
              }}>
                <span style={{ width: 4, height: 4, borderRadius: 999, background: "var(--midnight)" }}/>
                {r}
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  </>
);

const InstructionFileEditor = () => {
  const initial = `# RedGone instruction file
# Generated by AI from your conversation — edit directly if you'd like.
# Format: YAML.

categories:
  - name: Auto-Reply OK
    when: settlement OR newsletter OR meeting_ack
    action: auto_reply_thank_you, route_to: Ops
  - name: AI Drafts
    when: portfolio_review OR pricing OR quote OR sign_off
    action: draft_for_review
  - name: Human Sends
    when: rfp OR press OR media_inquiry
    action: notify_user, leave_in_inbox
  - name: Human Required
    when: account_access OR complaint OR first_time_client(<90d)
    action: surface_urgently, copy: compliance@redgone.io

compliance_mode: FCA
internal_policy: northwind-policy-v3.2.yml
escalation:
  - if: complaint OR regulator
    to: compliance@northwind-cap.com
`;
  return (
    <>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div className="micro">redgone.spec.yml · last edited by AI</div>
        <span className="mono" style={{ fontSize: 11, color: "var(--success-mint)" }}>● SYNCED</span>
      </div>
      <textarea
        defaultValue={initial}
        spellCheck={false}
        className="scroll"
        style={{
          width: "100%", flex: 1, marginTop: 12, padding: 16, borderRadius: 14,
          background: "var(--white-soft)", fontSize: 13, lineHeight: 1.55,
          fontFamily: "'JetBrains Mono', monospace", color: "var(--midnight)",
          border: "none", outline: "none", resize: "none",
          boxShadow: "var(--neu-in)",
        }}
      />
      <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 12 }}>
        <button className="neu-btn neu-btn-sm">Validate</button>
        <button className="neu-btn-redglow neu-btn-redglow-sm">Save & retrain</button>
      </div>
    </>
  );
};

window.SpecBuilder = SpecBuilder;
window.SpecPreview = SpecPreview;
window.InstructionFileEditor = InstructionFileEditor;
