// Generic UI primitives shared across screens.

const Card = ({ children, style, className = "", title, subtitle, action, padded = true, ...rest }) => {
  // Strip any non-DOM prop that may slip through if a caller passed extras.
  delete rest.padded;
  return (
  <div className={`hx-card ${className}`} style={style} {...rest}>
    {(title || action) && (
      <div className="hx-card-head">
        <div>
          {title && <div className="hx-card-title">{title}</div>}
          {subtitle && <div className="hx-card-sub">{subtitle}</div>}
        </div>
        {action}
      </div>
    )}
    <div className={padded ? "hx-card-body" : ""}>{children}</div>
    <style>{`
      .hx-card {
        background: var(--panel);
        border: 1px solid var(--line);
        border-radius: var(--r-md);
        box-shadow: var(--shadow-1);
        min-width: 0;
      }
      .hx-card-head {
        padding: var(--pad) var(--pad) 0 var(--pad);
        display: flex; justify-content: space-between; align-items: flex-start;
        gap: 12px;
      }
      .hx-card-title { font-size: 16px; font-weight: 600; letter-spacing: -.01em; color: var(--ink); }
      .hx-card-sub { color: var(--muted); font-size: 13px; margin-top: 4px; }
      .hx-card-body { padding: var(--pad); }
    `}</style>
  </div>
  );
};

const Btn = ({ children, kind = "primary", size = "md", icon, iconRight, onClick, disabled, style, type = "button", className = "", ...rest }) => {
  const cls = `hx-btn hx-btn-${kind} hx-btn-${size} ${className}`;
  return (
    <button type={type} disabled={disabled} onClick={onClick} className={cls} style={style} {...rest}>
      {icon && <span className="hx-btn-icon">{icon}</span>}
      <span>{children}</span>
      {iconRight && <span className="hx-btn-icon">{iconRight}</span>}
      <style>{`
        .hx-btn {
          display: inline-flex; align-items: center; gap: 6px;
          border: 1px solid transparent;
          border-radius: 8px;
          font-weight: 500;
          cursor: pointer;
          transition: background .12s ease, border-color .12s ease, color .12s ease, transform .04s ease;
          white-space: nowrap;
          line-height: 1;
        }
        .hx-btn:active { transform: translateY(.5px); }
        .hx-btn-icon { display: inline-flex; }
        .hx-btn-md { height: var(--row); padding: 0 14px; font-size: 14px; }
        .hx-btn-sm { height: 30px; padding: 0 10px; font-size: 13px; }
        .hx-btn-lg { height: 44px; padding: 0 18px; font-size: 15px; }
        .hx-btn-primary { background: var(--accent); color: var(--accent-ink); }
        .hx-btn-primary:hover { background: var(--accent-strong); }
        .hx-btn-secondary { background: var(--panel); color: var(--ink); border-color: var(--line); }
        .hx-btn-secondary:hover { background: var(--hover); }
        .hx-btn-ghost { background: transparent; color: var(--ink-2); }
        .hx-btn-ghost:hover { background: var(--hover); }
        .hx-btn-danger { background: transparent; color: var(--bad); border-color: var(--line); }
        .hx-btn-danger:hover { background: #fdecec; }
        .hx-btn:disabled { opacity: .55; cursor: not-allowed; }
      `}</style>
    </button>
  );
};

const Pill = ({ children, tone = "neutral", style }) => (
  <span className={`hx-pill hx-pill-${tone}`} style={style}>
    {children}
    <style>{`
      .hx-pill { display: inline-flex; align-items:center; padding: 2px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 500; letter-spacing: .01em; }
      .hx-pill-neutral { background: var(--line-2); color: var(--ink-2); }
      .hx-pill-accent { background: var(--accent-soft); color: var(--accent-strong); }
      .hx-pill-good { background: var(--good-soft); color: var(--good); }
      .hx-pill-warn { background: var(--warn-soft); color: var(--warn); }
      .hx-pill-info { background: var(--info-soft); color: var(--info-ink); }
    `}</style>
  </span>
);

const Input = ({ value, onChange, placeholder, prefix, suffix, type = "text", style, ...rest }) => (
  <label className="hx-input-wrap" style={style}>
    {prefix && <span className="hx-input-prefix">{prefix}</span>}
    <input type={type} value={value} onChange={onChange} placeholder={placeholder} {...rest} />
    {suffix && <span className="hx-input-suffix">{suffix}</span>}
    <style>{`
      .hx-input-wrap {
        display:flex; align-items:center; gap:6px;
        height: var(--row);
        background: var(--panel);
        border: 1px solid var(--line);
        border-radius: 8px;
        padding: 0 10px;
        transition: border-color .12s ease, box-shadow .12s ease;
      }
      .hx-input-wrap:focus-within {
        border-color: var(--accent);
        box-shadow: 0 0 0 3px color-mix(in oklab, var(--accent) 18%, transparent);
      }
      .hx-input-wrap input {
        border: none; outline: none; background: transparent; flex: 1; font: inherit;
        color: var(--ink);
      }
      .hx-input-prefix, .hx-input-suffix { color: var(--muted); display: inline-flex; }
    `}</style>
  </label>
);

const Toggle = ({ checked, onChange, label }) => (
  <button type="button" onClick={() => onChange(!checked)} className={`hx-tog ${checked ? "on" : ""}`} role="switch" aria-checked={checked} aria-label={label}>
    <span className="dot" />
    <style>{`
      .hx-tog { width: 36px; height: 20px; border-radius: 999px; background: var(--line); border: none; position: relative; cursor: pointer; padding: 0; transition: background .15s; }
      .hx-tog .dot { position:absolute; top:2px; left:2px; width:16px; height:16px; border-radius:50%; background:white; box-shadow: 0 1px 2px rgba(0,0,0,.2); transition: transform .15s ease; }
      .hx-tog.on { background: var(--accent); }
      .hx-tog.on .dot { transform: translateX(16px); }
    `}</style>
  </button>
);

// Avatar — initials in a colored circle. Color derived from name.
const Avatar = ({ name, size = 36, color }) => {
  const initials = name.split(" ").filter(Boolean).map(s => s[0]).slice(0,2).join("").toUpperCase();
  const palette = ["#3a7c5f", "#4a5dd0", "#a23f6e", "#b3691a", "#6b3aa3", "#0f7d8a", "#1f6fb3"];
  const idx = [...name].reduce((a, c) => a + c.charCodeAt(0), 0) % palette.length;
  const bg = color || palette[idx];
  return (
    <div style={{
      width: size, height: size, borderRadius: "50%",
      background: bg, color: "white",
      display: "flex", alignItems: "center", justifyContent: "center",
      fontSize: size * 0.36, fontWeight: 600, flexShrink: 0, letterSpacing: ".02em",
    }}>{initials}</div>
  );
};

const Crumbs = ({ items, onClick }) => (
  <nav className="hx-crumbs" aria-label="Breadcrumb">
    {items.map((it, i) => (
      <React.Fragment key={i}>
        <span
          className={`hx-crumb ${i === items.length - 1 ? "hx-crumb-last" : ""}`}
          onClick={() => onClick && onClick(it, i)}
          role={onClick ? "link" : undefined}
        >{it.label}</span>
        {i < items.length - 1 && <IconChevR size={12} className="hx-crumb-sep"/>}
      </React.Fragment>
    ))}
    <style>{`
      .hx-crumbs { display:flex; align-items:center; gap: 8px; color: var(--muted); font-size: 13.5px; }
      .hx-crumb { cursor: pointer; }
      .hx-crumb:hover { color: var(--ink-2); }
      .hx-crumb-last { color: var(--muted-2); cursor: default; }
      .hx-crumb-sep { color: var(--muted-2); }
    `}</style>
  </nav>
);

// Modal — overlay + dismissable card
const Modal = ({ open, onClose, title, children, footer, width = 460 }) => {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="hx-modal-overlay" onClick={onClose}>
      <div className="hx-modal" style={{ width }} onClick={(e) => e.stopPropagation()}>
        <div className="hx-modal-head">
          <div className="hx-modal-title">{title}</div>
          <button className="hx-modal-x" onClick={onClose} aria-label="Close"><IconClose size={18}/></button>
        </div>
        <div className="hx-modal-body">{children}</div>
        {footer && <div className="hx-modal-foot">{footer}</div>}
      </div>
      <style>{`
        .hx-modal-overlay {
          position: fixed; inset: 0; background: rgba(13,17,28,.45);
          display: flex; align-items: center; justify-content: center; z-index: 80;
          padding: 24px; animation: hxfade .12s ease both;
        }
        @keyframes hxfade { from { opacity: 0 } to { opacity: 1 } }
        .hx-modal {
          background: var(--panel); border-radius: var(--r-md);
          box-shadow: var(--shadow-modal); max-width: 100%;
          animation: hxpop .14s cubic-bezier(.2,.9,.3,1.2) both;
        }
        @keyframes hxpop { from { transform: translateY(8px) scale(.98); opacity: 0 } to { transform: none; opacity: 1 } }
        .hx-modal-head {
          display: flex; align-items: center; justify-content: space-between;
          padding: 18px 20px; border-bottom: 1px solid var(--line-2);
        }
        .hx-modal-title { font-size: 16px; font-weight: 600; }
        .hx-modal-x { background: transparent; border: none; cursor: pointer; color: var(--muted); padding: 4px; border-radius: 6px; display:inline-flex; }
        .hx-modal-x:hover { background: var(--hover); color: var(--ink); }
        .hx-modal-body { padding: 20px; }
        .hx-modal-foot { padding: 14px 20px; border-top: 1px solid var(--line-2); display: flex; justify-content: flex-end; gap: 8px; background: var(--panel-2); border-radius: 0 0 var(--r-md) var(--r-md); }
      `}</style>
    </div>
  );
};

// Toast — wires to window.__toast(msg, tone)
const ToastHost = () => {
  const [items, setItems] = React.useState([]);
  React.useEffect(() => {
    window.__toast = (msg, tone = "good") => {
      const id = Math.random().toString(36).slice(2);
      setItems(s => [...s, { id, msg, tone }]);
      setTimeout(() => setItems(s => s.filter(x => x.id !== id)), 2800);
    };
  }, []);
  return (
    <div className="hx-toasts" role="status" aria-live="polite">
      {items.map(t => (
        <div key={t.id} className={`hx-toast hx-toast-${t.tone}`}>
          <IconCheck size={16}/> <span>{t.msg}</span>
        </div>
      ))}
      <style>{`
        .hx-toasts { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); z-index: 90; display:flex; flex-direction:column; gap:8px; align-items: center; }
        .hx-toast { display: inline-flex; align-items: center; gap: 8px; padding: 10px 14px; border-radius: 10px; font-size: 13.5px; color: white; box-shadow: 0 8px 24px rgba(0,0,0,.18); animation: hxtin .2s cubic-bezier(.2,.9,.3,1.2) both; }
        @keyframes hxtin { from { transform: translateY(8px); opacity:0 } to { transform:none; opacity: 1 } }
        .hx-toast-good { background: #0e1a14; }
        .hx-toast-warn { background: #2a1f0e; }
      `}</style>
    </div>
  );
};

Object.assign(window, { Card, Btn, Pill, Input, Toggle, Avatar, Crumbs, Modal, ToastHost });
