/* Host shell — original "AI Cowork" surface. Three-pane:
   sidebar (workspace nav) · main chat thread · right-side context panel. */

function HIcon({ name, ...rest }) {
  const common = { width: 16, height: 16, fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round', ...rest };
  switch (name) {
    case 'chat':    return <svg viewBox="0 0 16 16" {...common}><path d="M2 3.5h12v8H7L4 14V11.5H2z" /></svg>;
    case 'cowork': return <svg viewBox="0 0 16 16" {...common}><path d="M3 5h10M3 8h10M3 11h10" /><circle cx="2" cy="5" r="0.6" fill="currentColor" stroke="none" /><circle cx="2" cy="8" r="0.6" fill="currentColor" stroke="none" /><circle cx="2" cy="11" r="0.6" fill="currentColor" stroke="none" /></svg>;
    case 'code':    return <svg viewBox="0 0 16 16" {...common}><path d="M6 5L2.5 8 6 11M10 5l3.5 3L10 11" /></svg>;
    case 'plus':    return <svg viewBox="0 0 16 16" {...common}><path d="M8 3v10M3 8h10" /></svg>;
    case 'folder':  return <svg viewBox="0 0 16 16" {...common}><path d="M2 5l2-2h3l1 1.5h6v8H2z" /></svg>;
    case 'clock':   return <svg viewBox="0 0 16 16" {...common}><circle cx="8" cy="8" r="5.5" /><path d="M8 5v3l2 1.5" /></svg>;
    case 'spark':   return <svg viewBox="0 0 16 16" {...common}><path d="M8 2v12M2 8h12M3.5 3.5l9 9M12.5 3.5l-9 9" /></svg>;
    case 'bell':    return <svg viewBox="0 0 16 16" {...common}><path d="M4 12V8a4 4 0 018 0v4l1 1.5H3z" /><path d="M6.5 13.5a1.5 1.5 0 003 0" /></svg>;
    case 'box':     return <svg viewBox="0 0 16 16" {...common}><rect x="2.5" y="2.5" width="11" height="11" rx="1.5" /></svg>;
    case 'sidebar': return <svg viewBox="0 0 16 16" {...common}><rect x="2" y="3" width="12" height="10" rx="1.5" /><path d="M6 3v10" /></svg>;
    case 'search':  return <svg viewBox="0 0 16 16" {...common}><circle cx="7" cy="7" r="4" /><path d="M10 10l3 3" /></svg>;
    case 'caret':   return <svg viewBox="0 0 16 16" {...common}><path d="M5 6l3 3 3-3" /></svg>;
    case 'caretRight': return <svg viewBox="0 0 16 16" {...common}><path d="M6 4l3 4-3 4" /></svg>;
    case 'mic':     return <svg viewBox="0 0 16 16" {...common}><rect x="6" y="2" width="4" height="8" rx="2" /><path d="M3.5 8a4.5 4.5 0 009 0M8 12.5V14" /></svg>;
    case 'hand':    return <svg viewBox="0 0 16 16" {...common}><path d="M5 10V5a1.5 1.5 0 113 0v3M8 8V4a1.5 1.5 0 113 0v5M5.5 10V7a1.5 1.5 0 10-3 0v3.5a4 4 0 008 0V9" /></svg>;
    case 'arrowUp': return <svg viewBox="0 0 16 16" {...common}><path d="M8 13V4M4 7l4-3 4 3" /></svg>;
    case 'thumbUp': return <svg viewBox="0 0 16 16" {...common}><path d="M3 14V8h2l2-5h1l-1 4h5l-1 7H3z" /></svg>;
    case 'thumbDown': return <svg viewBox="0 0 16 16" {...common}><path d="M3 2v6h2l2 5h1l-1-4h5l-1-7H3z" /></svg>;
    case 'copy':    return <svg viewBox="0 0 16 16" {...common}><rect x="5" y="5" width="8" height="8" rx="1.5" /><path d="M3 11V3.5A1.5 1.5 0 014.5 2H11" /></svg>;
    default: return null;
  }
}
window.HostIcon = HIcon;

/* ─ Real AgntUX wordmark, inline + scaled to whatever height the context
   gives it via CSS. The gradient on "UX" matches the brand. ─ */
function AgntuxLogo({ height = 18 }) {
  return (
    <svg viewBox="0 0 180 48" style={{ height, width: 'auto', display: 'block' }} xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="ux-grad-card" x1="108" y1="8" x2="176" y2="42" gradientUnits="userSpaceOnUse">
          <stop offset="0%" stopColor="#19e6c8" />
          <stop offset="50%" stopColor="#1a8cff" />
          <stop offset="100%" stopColor="#7c5cff" />
        </linearGradient>
      </defs>
      <text x="0" y="37" fontFamily="Inter, system-ui, -apple-system, sans-serif"
            fontSize="38" fontWeight="800" letterSpacing="-1.5">
        <tspan fill="#1a1a1a">Agnt</tspan>
        <tspan fill="url(#ux-grad-card)">UX</tspan>
      </text>
    </svg>
  );
}
window.AgntuxLogo = AgntuxLogo;

/* Brand marks used inside connector tool-call cards. Recognizable but
   built from simple shapes — no third-party assets required. */
function SlackMark({ size = 18 }) {
  // 4-color hashtag (Slack's familiar visual cue)
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} aria-hidden="true">
      <rect x="2" y="10" width="20" height="2.4" rx="1.2" fill="#36c5f0" />
      <rect x="2" y="13.6" width="20" height="2.4" rx="1.2" fill="#2eb67d" />
      <rect x="9" y="2" width="2.4" height="20" rx="1.2" fill="#e01e5a" />
      <rect x="12.6" y="2" width="2.4" height="20" rx="1.2" fill="#ecb22e" />
    </svg>
  );
}
function GmailMark({ size = 18 }) {
  // Stylized envelope with red "M" suggestion
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} aria-hidden="true">
      <rect x="2" y="5" width="20" height="14" rx="2" fill="#ffffff" stroke="#e0e0e0" strokeWidth="1" />
      <path d="M3 6l9 7 9-7" stroke="#ea4335" strokeWidth="1.6" fill="none" strokeLinejoin="round" />
      <path d="M3 7v11" stroke="#4285f4" strokeWidth="1.6" />
      <path d="M21 7v11" stroke="#34a853" strokeWidth="1.6" />
    </svg>
  );
}
window.SlackMark = SlackMark;
window.GmailMark = GmailMark;

function Sidebar() {
  return (
    <aside className="side">
      <div className="side-window">
        <span className="traffic red" />
        <span className="traffic yel" />
        <span className="traffic grn" />
        <div style={{ flex: 1 }} />
        <HIcon name="sidebar" style={{ color: 'var(--text-mute)' }} />
        <HIcon name="search" style={{ color: 'var(--text-mute)' }} />
      </div>

      <div className="side-tabs">
        <div className="side-tab"><HIcon name="chat" /> Chat</div>
        <div className="side-tab active"><HIcon name="cowork" /> Cowork</div>
        <div className="side-tab"><HIcon name="code" /> Code</div>
      </div>

      <div className="side-row"><HIcon name="plus" style={{ color: 'var(--text)' }} /> New task</div>
      <div className="side-row"><HIcon name="folder" /> Projects</div>
      <div className="side-row"><HIcon name="clock" /> Scheduled</div>
      <div className="side-row"><HIcon name="spark" /> Live artifacts</div>
      <div className="side-row"><HIcon name="bell" /> Dispatch <span className="count" style={{ background: 'var(--accent-soft)', color: 'var(--accent)' }}>Beta</span></div>
      <div className="side-row"><HIcon name="box" /> Customize</div>

      <div className="side-label">Scheduled</div>
      <div className="side-row"><span className="dot" /> AgntUX slack ingest <span className="count">43 new</span></div>
      <div className="side-row"><span className="dot filled" /> AgntUX gmail ingest <span className="count">47 new</span></div>

      <div className="side-label">Recents</div>
      <div className="side-row active"><span className="dot" /> Untitled task</div>
      <div className="side-row"><span className="dot" /> Reschedule Northstream sync</div>
      <div className="side-row"><span className="dot" /> Catalyst v2→v3 sign-off</div>
      <div className="side-row"><span className="dot" /> Webhook errors postmortem</div>
      <div className="side-row"><span className="dot" /> Skyforge renewal review</div>

      <div className="side-user">
        <div className="avatar">J</div>
        <div style={{ flex: 1 }}>
          <div className="name">Jamie</div>
          <div className="plan">Workspace · Pro</div>
        </div>
        <HIcon name="caret" style={{ color: 'var(--text-mute)' }} />
      </div>
    </aside>
  );
}

function RightPanel({ contextActive }) {
  return (
    <aside className="right">
      <div className="right-card">
        <div className="title">
          Working folder
          <span className="caret"><HIcon name="caret" /></span>
        </div>
        <div className="row" style={{ marginTop: 6 }}>
          <HIcon name="caretRight" /> Scratchpad
        </div>
        <div className="row">
          <HIcon name="caretRight" /> actions/
        </div>
        <div className="row">
          <HIcon name="caretRight" /> drafts/
        </div>
      </div>

      <div className="right-card">
        <div className="title">
          Context
          <span className="caret"><HIcon name="caret" /></span>
        </div>
        <div className="body" style={{ fontSize: 12 }}>
          {contextActive ? (
            <>
              <div className="row"><HIcon name="box" /> agntux-core / view-tool</div>
              <div className="row"><HIcon name="box" /> .agntux/actions/*</div>
              <div className="row"><HIcon name="folder" /> 3 files read</div>
            </>
          ) : (
            <span style={{ color: 'var(--text-dim)' }}>Track tools and files used in this task.</span>
          )}
        </div>
      </div>
    </aside>
  );
}

window.Sidebar = Sidebar;
window.RightPanel = RightPanel;

/* ── chat thread message types ───────────────────────────────── */

/* User message — supports `kind` to style /commands vs long prompts.
   For /command messages, the slash prefix gets the blue accent. For
   long prompt envelopes we render with .compact and dim styling so
   they read as "auto-filled prompt" without dominating the thread. */
function UserMessage({ text, compact }) {
  // Render guillemets («») in a dimmer tone so the envelope reads cleanly
  const parts = String(text).split(/(«[^»]*»)/g);
  const isSlash = /^\/[a-z]/i.test(text.trim());
  return (
    <div className={['msg-user fade-up', compact ? 'compact' : ''].join(' ')}>
      {parts.map((p, i) => {
        if (p.startsWith('«') && p.endsWith('»')) {
          return <span className="guill" key={i}>{p}</span>;
        }
        if (isSlash && i === 0) {
          const m = p.match(/^(\/\S+)(.*)/);
          if (m) {
            return (
              <React.Fragment key={i}>
                <span className="slash">{m[1]}</span>{m[2]}
              </React.Fragment>
            );
          }
        }
        return <React.Fragment key={i}>{p}</React.Fragment>;
      })}
    </div>
  );
}

/* Simple gray "Read 3 files, loaded tools..." status line. */
function ToolStatus({ text }) {
  return (
    <div className="tool-status fade-in">
      <svg viewBox="0 0 16 16" width="14" height="14" fill="none" className="check">
        <path d="M3 8.5l3 3 7-7" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
      <span>{text}</span>
      <HIcon name="caretRight" className="caret" />
    </div>
  );
}

function AssistantOrb() {
  return <div className="streaming-orb fade-in" />;
}

function AssistMessageActions() {
  return (
    <div className="assist-actions">
      <HIcon name="copy" />
      <HIcon name="thumbUp" />
      <HIcon name="thumbDown" />
    </div>
  );
}

/* Connector tool call card — used when a Slack/Gmail connector tool
   is actually being executed by the host. Shows brand logo, tool
   name, and the in-flight/done state. */
function ConnectorCall({ brand, tool, desc, state, result }) {
  // state: 'running' | 'done'
  const Mark = brand === 'slack' ? SlackMark : GmailMark;
  return (
    <div className="tool-call fade-up">
      <div className={`brand-mark ${brand}`}>
        <Mark size={20} />
      </div>
      <div className="meta">
        <div className="title">
          {brand === 'slack' ? 'Slack Connector' : 'Gmail Connector'}
          <span className="step">{tool}</span>
        </div>
        <div className={state === 'done' ? 'result ok' : 'desc'}>
          {state === 'done' ? result : desc}
        </div>
      </div>
      {state === 'running' ? (
        <span className="status-pill">
          <span className="spin-sm" /> Running
        </span>
      ) : (
        <span className="status-pill ok">
          <svg viewBox="0 0 16 16" width="11" height="11" fill="none">
            <path d="M3 8.5l3 3 7-7" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
          Sent
        </span>
      )}
    </div>
  );
}

/* ── Composer (always visible) ────────────────────────────────
   `text` is the current input; when text is empty the placeholder
   shows. When `pressedSend` is true the send button gets a pulse.
   The send button is dimmed when the composer is empty (no input). */
function Composer({ text, caretBlink, sendBtnRef, pressedSend, multiline }) {
  const hasText = text && text.length > 0;
  const isSlash = hasText && /^\/[a-z]/i.test(text.trim());
  const isShort = !text || text.length < 80;

  // Split out guillemets for soft-color styling on prompt envelopes
  const parts = String(text || '').split(/(«[^»]*»)/g);

  return (
    <div className="composer-wrap">
      <div className="composer">
        <div className={['composer-input', isShort ? 'short' : ''].join(' ')}>
          {!hasText ? (
            <span className="placeholder">Write a message…</span>
          ) : (
            <span className="typed">
              {parts.map((p, i) => {
                if (p.startsWith('«') && p.endsWith('»')) {
                  return <span className="guill" key={i}>{p}</span>;
                }
                if (isSlash && i === 0) {
                  const m = p.match(/^(\/\S+)(.*)/);
                  if (m) {
                    return (
                      <React.Fragment key={i}>
                        <span className="slash">{m[1]}</span>{m[2]}
                      </React.Fragment>
                    );
                  }
                }
                return <React.Fragment key={i}>{p}</React.Fragment>;
              })}
            </span>
          )}
          {caretBlink && hasText ? <span className="composer-caret" /> : null}
          {caretBlink && !hasText ? <span className="composer-caret" /> : null}
        </div>
        <div className="composer-bar">
          <div className="plus">+</div>
          <div className="ask">
            <HIcon name="hand" /> Ask <HIcon name="caret" />
          </div>
          <div className="spacer" />
          <div className="model">Latest <HIcon name="caret" /></div>
          <div className="mic"><HIcon name="mic" /></div>
          <button
            ref={sendBtnRef}
            type="button"
            className={['send-btn', hasText ? '' : 'dim', pressedSend ? 'pulse' : ''].join(' ')}
            aria-label="Send"
          >
            <HIcon name="arrowUp" />
          </button>
        </div>
      </div>
      <div className="disclaimer">
        AI can make mistakes. Please double-check responses.
      </div>
    </div>
  );
}

window.UserMessage = UserMessage;
window.ToolStatus = ToolStatus;
window.AssistantOrb = AssistantOrb;
window.AssistMessageActions = AssistMessageActions;
window.ConnectorCall = ConnectorCall;
window.Composer = Composer;
