// Shared UI primitives & icons for the Council Meetings module
// Icons: hand-rolled monoline SVGs (admin-style, 16px stroke 1.6)

const Icon = ({ name, size = 16, className = "" }) => {
  const s = size;
  const stroke = 1.6;
  const common = {
    width: s, height: s, viewBox: "0 0 24 24",
    fill: "none", stroke: "currentColor",
    strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round",
    className,
  };
  switch (name) {
    case "dashboard": return <svg {...common}><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></svg>;
    case "calendar":  return <svg {...common}><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 9h18"/><path d="M8 3v4M16 3v4"/></svg>;
    case "file-text": return <svg {...common}><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><path d="M14 3v6h6"/><path d="M8 13h8M8 17h6"/></svg>;
    case "list":      return <svg {...common}><path d="M8 6h13M8 12h13M8 18h13"/><circle cx="3.5" cy="6"  r="1"/><circle cx="3.5" cy="12" r="1"/><circle cx="3.5" cy="18" r="1"/></svg>;
    case "gavel":     return <svg {...common}><path d="m14 14-7 7"/><path d="M9 7l4-4 7 7-4 4z"/><path d="M14 13l3 3"/><path d="M5 21h6"/></svg>;
    case "users":     return <svg {...common}><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>;
    case "settings":  return <svg {...common}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>;
    case "search":    return <svg {...common}><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>;
    case "bell":      return <svg {...common}><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></svg>;
    case "plus":      return <svg {...common}><path d="M12 5v14M5 12h14"/></svg>;
    case "chevron-down": return <svg {...common}><path d="m6 9 6 6 6-6"/></svg>;
    case "chevron-right": return <svg {...common}><path d="m9 6 6 6-6 6"/></svg>;
    case "chevron-left":  return <svg {...common}><path d="m15 6-6 6 6 6"/></svg>;
    case "more":      return <svg {...common}><circle cx="12" cy="12" r="1.2"/><circle cx="19" cy="12" r="1.2"/><circle cx="5" cy="12" r="1.2"/></svg>;
    case "filter":    return <svg {...common}><path d="M22 3H2l8 9.46V19l4 2v-8.54z"/></svg>;
    case "x":         return <svg {...common}><path d="M18 6 6 18M6 6l12 12"/></svg>;
    case "edit":      return <svg {...common}><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4Z"/></svg>;
    case "trash":     return <svg {...common}><path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="m19 6-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>;
    case "play":      return <svg {...common}><polygon points="5 3 19 12 5 21 5 3" fill="currentColor"/></svg>;
    case "stop":      return <svg {...common}><rect x="6" y="6" width="12" height="12" rx="1" fill="currentColor"/></svg>;
    case "check":     return <svg {...common}><path d="m5 12 5 5L20 7"/></svg>;
    case "check-circle": return <svg {...common}><circle cx="12" cy="12" r="9"/><path d="m9 12 2 2 4-4"/></svg>;
    case "circle":    return <svg {...common}><circle cx="12" cy="12" r="9"/></svg>;
    case "minus-circle": return <svg {...common}><circle cx="12" cy="12" r="9"/><path d="M8 12h8"/></svg>;
    case "x-circle":  return <svg {...common}><circle cx="12" cy="12" r="9"/><path d="m15 9-6 6M9 9l6 6"/></svg>;
    case "alert":     return <svg {...common}><path d="m10.29 3.86-8.18 14a2 2 0 0 0 1.71 3h16.36a2 2 0 0 0 1.71-3l-8.18-14a2 2 0 0 0-3.42 0Z"/><path d="M12 9v4M12 17h.01"/></svg>;
    case "clock":     return <svg {...common}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>;
    case "map-pin":   return <svg {...common}><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z"/><circle cx="12" cy="10" r="3"/></svg>;
    case "tag":       return <svg {...common}><path d="M20.59 13.41 12 22l-9-9V3h10z"/><circle cx="7" cy="7" r="1.5"/></svg>;
    case "paperclip": return <svg {...common}><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66L9.41 17.41a2 2 0 0 1-2.83-2.83l8.49-8.49"/></svg>;
    case "download":  return <svg {...common}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M7 10l5 5 5-5"/><path d="M12 15V3"/></svg>;
    case "upload":    return <svg {...common}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M17 8l-5-5-5 5"/><path d="M12 3v12"/></svg>;
    case "external":  return <svg {...common}><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><path d="M15 3h6v6"/><path d="m10 14 11-11"/></svg>;
    case "presentation": return <svg {...common}><path d="M2 3h20"/><path d="M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3"/><path d="m12 16-3 5M12 16l3 5M12 12V8"/></svg>;
    case "lock":      return <svg {...common}><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>;
    case "info":      return <svg {...common}><circle cx="12" cy="12" r="9"/><path d="M12 16v-4M12 8h.01"/></svg>;
    case "save":      return <svg {...common}><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><path d="M17 21v-8H7v8M7 3v5h8"/></svg>;
    case "drag":      return <svg {...common}><circle cx="9" cy="6" r="1"/><circle cx="15" cy="6" r="1"/><circle cx="9" cy="12" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="9" cy="18" r="1"/><circle cx="15" cy="18" r="1"/></svg>;
    case "eye":       return <svg {...common}><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>;
    case "send":      return <svg {...common}><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>;
    case "vote":      return <svg {...common}><path d="M9 11 12 14l4-6"/><path d="M21 12c0 5-4 9-9 9s-9-4-9-9 4-9 9-9c2 0 4 .7 5.5 2"/></svg>;
    case "archive":   return <svg {...common}><rect x="3" y="3" width="18" height="5" rx="1"/><path d="M5 8v11a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"/><path d="M10 12h4"/></svg>;
    default: return <svg {...common}><circle cx="12" cy="12" r="9"/></svg>;
  }
};

// ============================================================
// Status pill
// ============================================================
const STATUS_MAP = {
  "Draft":         { tone: "neutral", label: "Draft" },
  "Scheduled":     { tone: "info",    label: "Scheduled" },
  "In Progress":   { tone: "warning", label: "In Progress" },
  "Completed":     { tone: "success", label: "Completed" },
  "Cancelled":     { tone: "neutral", label: "Cancelled" },
  "Submitted":     { tone: "info",    label: "Submitted" },
  "Added to agenda": { tone: "brand", label: "Added to agenda" },
  "Voted":         { tone: "warning", label: "Voted" },
  "Resolved":      { tone: "success", label: "Resolved" },
  "Rejected":      { tone: "danger",  label: "Rejected" },
  "Pending debate": { tone: "neutral", label: "Pending debate" },
  "Debating":      { tone: "warning", label: "Debating" },
  "Ready for vote": { tone: "info",    label: "Ready for vote" },
};

const StatusPill = ({ status, dot = true }) => {
  const cfg = STATUS_MAP[status] || { tone: "neutral", label: status };
  return (
    <span className={`badge badge--${cfg.tone}${dot ? " badge--dot" : ""}`}>{cfg.label}</span>
  );
};

const TypeBadge = ({ type }) => {
  const tone = type === "Emergency" ? "danger" : "outline";
  return <span className={`badge badge--${tone}`}>{type}</span>;
};

// ============================================================
// Avatar / stacks
// ============================================================
const Avatar = ({ p, size = "md" }) => {
  if (!p) return null;
  const cls = size === "sm" ? "avatar avatar--sm" : size === "lg" ? "avatar avatar--lg" : "avatar";
  // Deterministic hue from initials
  const hue = (p.initials.charCodeAt(0) + p.initials.charCodeAt(1)) % 360;
  return (
    <span
      className={cls}
      style={{
        background: `oklch(0.88 0.04 ${hue})`,
        color: `oklch(0.32 0.06 ${hue})`,
      }}
      title={p.name}
    >{p.initials}</span>
  );
};

const AvatarStack = ({ ids, max = 4 }) => {
  const list = ids.slice(0, max).map(id => getParticipant(id)).filter(Boolean);
  const overflow = ids.length - list.length;
  return (
    <span className="avatar-stack">
      {list.map(p => <Avatar key={p.id} p={p} size="sm" />)}
      {overflow > 0 && (
        <span className="avatar avatar--sm" style={{ background: "#e3e6eb", color: "#6b7280" }}>+{overflow}</span>
      )}
    </span>
  );
};

// ============================================================
// Empty state
// ============================================================
const Empty = ({ icon = "file-text", title, text, action }) => (
  <div className="empty">
    <div className="empty__icon"><Icon name={icon} size={20} /></div>
    <p className="empty__title">{title}</p>
    {text && <p className="empty__text">{text}</p>}
    {action}
  </div>
);

// ============================================================
// Modal
// ============================================================
const Modal = ({ title, onClose, children, footer, size = "md" }) => (
  <div className="modal-backdrop" onClick={onClose}>
    <div className={`modal ${size === "lg" ? "modal--lg" : ""}`} onClick={e => e.stopPropagation()}>
      <div className="modal__header">
        <h3 className="modal__title">{title}</h3>
        <button className="btn btn--ghost btn--icon btn--sm modal__close" onClick={onClose} aria-label="Close">
          <Icon name="x" />
        </button>
      </div>
      <div className="modal__body">{children}</div>
      {footer && <div className="modal__footer">{footer}</div>}
    </div>
  </div>
);

// ============================================================
// Vote bar
// ============================================================
const VoteBar = ({ vote }) => {
  if (!vote) return <span className="muted">—</span>;
  const total = vote.for + vote.against + vote.abstain;
  if (total === 0) return <span className="muted">—</span>;
  const pct = (n) => `${(n/total*100).toFixed(0)}%`;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 4, minWidth: 140 }}>
      <div className="votebar">
        <div className="votebar__seg votebar__seg--for" style={{ width: pct(vote.for) }} />
        <div className="votebar__seg votebar__seg--against" style={{ width: pct(vote.against) }} />
        <div className="votebar__seg votebar__seg--abstain" style={{ width: pct(vote.abstain) }} />
      </div>
      <div className="vote-summary">
        <span className="vote-summary__seg vote-summary__seg--for">For {vote.for}</span>
        <span className="vote-summary__seg vote-summary__seg--against">Against {vote.against}</span>
        <span className="vote-summary__seg vote-summary__seg--abstain">Abstain {vote.abstain}</span>
      </div>
    </div>
  );
};

const VoteResultPill = ({ vote }) => {
  if (!vote) return <span className="muted">—</span>;
  const total = vote.for + vote.against + vote.abstain;
  const passed = vote.for > vote.against;
  return (
    <span className={`badge badge--${passed ? "success" : "danger"} badge--dot`}>
      {passed ? "Passed" : "Rejected"} · {vote.for}–{vote.against}{vote.abstain ? `–${vote.abstain}` : ""}
    </span>
  );
};

// ============================================================
// Attachment
// ============================================================
const Attachment = ({ a }) => {
  const ext = (a.type || a.name.split(".").pop() || "doc").toLowerCase();
  const cls = ext.includes("pdf") ? "pdf" : ext.includes("xls") ? "xlsx" : ext.includes("img") || ext.includes("png") || ext.includes("jpg") ? "img" : "doc";
  const label = cls === "img" ? "IMG" : cls.toUpperCase();
  return (
    <div className="attachment">
      <span className={`attachment__icon attachment__icon--${cls}`}>{label}</span>
      <div style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis" }}>
        <div className="attachment__name" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{a.name}</div>
        <div className="attachment__size">{a.size}</div>
      </div>
      <button className="btn btn--ghost btn--icon btn--sm" title="Download">
        <Icon name="download" size={14} />
      </button>
    </div>
  );
};

// ============================================================
// Date helpers
// ============================================================
const fmtDate = (s) => {
  if (!s) return "—";
  const d = new Date(s);
  return d.toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" });
};
const fmtDateTime = (s) => {
  if (!s) return "—";
  const d = new Date(s);
  return d.toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" }) +
         " · " + d.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
};
const relDate = (s) => {
  if (!s) return "—";
  const d = new Date(s);
  const now = new Date();
  const days = Math.round((d - now) / (1000*60*60*24));
  if (days === 0) return "Today";
  if (days === 1) return "Tomorrow";
  if (days === -1) return "Yesterday";
  if (days > 0 && days < 14) return `in ${days} days`;
  if (days < 0 && days > -14) return `${-days} days ago`;
  return fmtDate(s);
};

// ============================================================
// Toast (basic)
// ============================================================
const ToastContext = React.createContext(null);
const ToastProvider = ({ children }) => {
  const [toasts, setToasts] = React.useState([]);
  const push = (msg, tone = "info") => {
    const id = Math.random().toString(36).slice(2);
    setToasts((t) => [...t, { id, msg, tone }]);
    setTimeout(() => setToasts((t) => t.filter(x => x.id !== id)), 2600);
  };
  return (
    <ToastContext.Provider value={push}>
      {children}
      <div className="toast-container">
        {toasts.map(t => (
          <div key={t.id} className={`toast toast--${t.tone}`}>
            <Icon name={t.tone === "success" ? "check-circle" : "info"} size={14} />
            {t.msg}
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  );
};
const useToast = () => React.useContext(ToastContext);

// Export
Object.assign(window, {
  Icon, StatusPill, TypeBadge, Avatar, AvatarStack,
  Empty, Modal, VoteBar, VoteResultPill, Attachment,
  fmtDate, fmtDateTime, relDate,
  ToastProvider, useToast,
});
