// States.jsx — Skeleton, EmptyState, ErrorState, Toast.
// Addresses Renée C-3 ("loading/empty/error state system, client-first").

// ----- Skeleton primitives ----------------------------------------------

const Skel = ({ w = "100%", h = 14, r = 4, style }) => (
  <span className="sk" style={{ width: w, height: h, borderRadius: r, ...style }} />
);

const SkelRow = ({ children }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 12 }}>{children}</div>
);

// ----- EmptyState -------------------------------------------------------

const EmptyState = ({ icon = "accounts", title, body, action, secondary, tone = "neutral" }) => (
  <div className="state-frame">
    <div className={`state-icon ${tone === "warning" ? "state-icon--warning" : tone === "danger" ? "state-icon--danger" : ""}`}>
      <Icon name={icon} size={22} stroke={1.4} />
    </div>
    <div className="state-heading">{title}</div>
    {body && <div className="state-body">{body}</div>}
    {(action || secondary) && (
      <div style={{ display: "flex", gap: 8, marginTop: 4 }}>
        {secondary && (
          <button className="btn btn--secondary btn--sm" type="button" onClick={secondary.onClick}>
            {secondary.label}
          </button>
        )}
        {action && (
          <button className="btn btn--primary btn--sm" type="button" onClick={action.onClick}>
            {action.icon && <Icon name={action.icon} size={12} stroke={1.7} />}
            {action.label}
          </button>
        )}
      </div>
    )}
  </div>
);

// ----- ErrorState -------------------------------------------------------

const ErrorState = ({ title = "Couldn't load this", body, onRetry, technical }) => {
  const [showTech, setShowTech] = React.useState(false);
  return (
    <div className="state-frame">
      <div className="state-icon state-icon--danger">
        <Icon name="alert" size={22} stroke={1.6} />
      </div>
      <div className="state-heading">{title}</div>
      {body && <div className="state-body">{body}</div>}
      <div style={{ display: "flex", gap: 8, marginTop: 4 }}>
        {technical && (
          <button className="btn btn--ghost btn--sm" type="button" onClick={() => setShowTech(!showTech)}>
            {showTech ? "Hide details" : "Show details"}
          </button>
        )}
        {onRetry && (
          <button className="btn btn--primary btn--sm" type="button" onClick={onRetry}>
            <Icon name="refresh" size={12} stroke={1.7} />
            Retry
          </button>
        )}
      </div>
      {showTech && technical && (
        <pre style={{
          marginTop: 8, padding: 10,
          background: "var(--bg-alt)",
          border: "1px solid var(--border)",
          borderRadius: 6,
          font: '400 11px/16px var(--font-mono)',
          color: "var(--fg-subtle)",
          textAlign: "left",
          whiteSpace: "pre-wrap", wordBreak: "break-all",
          maxWidth: 460,
        }}>{technical}</pre>
      )}
    </div>
  );
};

// ----- Toast stack ------------------------------------------------------

const ToastStack = ({ toasts, onDismiss }) => (
  <div className="toast-stack" role="region" aria-live="polite">
    {toasts.map((t) => (
      <div key={t.id} className={`toast toast--${t.tone || "info"}`}>
        <span className="toast-icon">
          <Icon
            name={t.tone === "success" ? "check" : t.tone === "error" ? "alert" : t.tone === "warning" ? "alert" : "info"}
            size={16} stroke={1.7}
          />
        </span>
        <div className="toast-body">
          <div className="toast-title">{t.title}</div>
          {t.sub && <div className="toast-sub">{t.sub}</div>}
        </div>
        {t.action && (
          <button className="btn btn--text btn--sm" type="button" onClick={t.action.onClick}>
            {t.action.label}
          </button>
        )}
        <button className="toast-close" type="button" aria-label="Dismiss" onClick={() => onDismiss(t.id)}>
          <Icon name="cross" size={14} stroke={1.6} />
        </button>
      </div>
    ))}
  </div>
);

// Hook for toasts
const useToasts = () => {
  const [toasts, setToasts] = React.useState([]);
  const push = React.useCallback((t) => {
    const id = Math.random().toString(36).slice(2, 9);
    setToasts((prev) => [...prev, { id, ...t }]);
    if (t.timeout !== 0) {
      const ms = t.timeout || 4500;
      setTimeout(() => setToasts((prev) => prev.filter((x) => x.id !== id)), ms);
    }
    return id;
  }, []);
  const dismiss = React.useCallback((id) => {
    setToasts((prev) => prev.filter((t) => t.id !== id));
  }, []);
  return { toasts, push, dismiss };
};

// ----- Page-level scaffolds ---------------------------------------------
// Reusable loading / error views so every route can carry the C-3 system,
// not just Facility Detail.

const PageHeaderSkel = () => (
  <div>
    <Skel w={70} h={11} />
    <div style={{ height: 12 }} />
    <Skel w={240} h={32} r={6} />
    <div style={{ height: 12 }} />
    <Skel w={420} h={16} />
  </div>
);

const KpiStripSkel = () => (
  <div style={{ display: "flex", gap: 16, flexWrap: "wrap" }}>
    <div className="card" style={{ flex: "2 1 320px", padding: "24px 28px" }}>
      <Skel w={90} h={11} /><div style={{ height: 12 }} />
      <Skel w={220} h={48} r={6} /><div style={{ height: 10 }} />
      <Skel w={180} h={14} />
    </div>
    <div className="card" style={{ flex: "3 1 480px", display: "flex", padding: 0 }}>
      {[0,1,2,3].map(i => (
        <div key={i} style={{ flex: 1, padding: "20px 24px", borderRight: i < 3 ? "1px solid var(--border)" : "none" }}>
          <Skel w={"80%"} h={11} /><div style={{ height: 10 }} />
          <Skel w={"60%"} h={22} /><div style={{ height: 8 }} />
          <Skel w={"70%"} h={12} />
        </div>
      ))}
    </div>
  </div>
);

const CardGridSkel = ({ count = 6, minH = 180 }) => (
  <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))", gap: 16 }}>
    {Array.from({ length: count }).map((_, i) => (
      <div key={i} className="card" style={{ minHeight: minH, display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <div><Skel w={140} h={18} /><div style={{ height: 6 }} /><Skel w={90} h={12} /></div>
          <Skel w={70} h={20} r={999} />
        </div>
        <div style={{ borderTop: "1px solid var(--border)", paddingTop: 14, display: "flex", gap: 16 }}>
          <div style={{ flex: 1 }}><Skel w={"70%"} h={11} /><div style={{ height: 6 }} /><Skel w={"50%"} h={18} /></div>
          <div style={{ flex: 1 }}><Skel w={"70%"} h={11} /><div style={{ height: 6 }} /><Skel w={"50%"} h={18} /></div>
          <div style={{ flex: 1 }}><Skel w={"70%"} h={11} /><div style={{ height: 6 }} /><Skel w={"50%"} h={18} /></div>
        </div>
        <Skel w={"100%"} h={3} r={2} />
        <div style={{ display: "flex", gap: 6 }}><Skel w={60} h={18} r={999}/><Skel w={60} h={18} r={999}/></div>
      </div>
    ))}
  </div>
);

const RowsSkel = ({ count = 4 }) => (
  <section className="card" style={{ padding: 0 }}>
    <div style={{ padding: "20px 24px 16px" }}>
      <Skel w={70} h={11} /><div style={{ height: 8 }} /><Skel w={260} h={26} />
    </div>
    {Array.from({ length: count }).map((_, i) => (
      <div key={i} style={{ display: "flex", alignItems: "center", gap: 20, padding: "18px 24px", borderTop: "1px solid var(--border)" }}>
        <Skel w={32} h={32} r={8} />
        <div style={{ flex: 1 }}><Skel w={160} h={16} /><div style={{ height: 6 }} /><Skel w={220} h={12} /></div>
        <Skel w={80} h={16} /><Skel w={80} h={16} /><Skel w={120} h={28} r={8} />
      </div>
    ))}
  </section>
);

// Per-page loading shape
const PageSkeleton = ({ shape = "dashboard" }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 28 }} aria-busy="true">
    <PageHeaderSkel />
    {shape === "dashboard" && (<><KpiStripSkel /><RowsSkel count={3} /><CardGridSkel count={6} /></>)}
    {shape === "list"      && (<><KpiStripSkel /><CardGridSkel count={9} /></>)}
    {shape === "rows"      && (<><KpiStripSkel /><RowsSkel count={6} /></>)}
    {shape === "profile"   && (<><div className="card" style={{ minHeight: 160 }} /><RowsSkel count={4} /><RowsSkel count={3} /></>)}
  </div>
);

// Page-level error — wraps ErrorState in a card with the page header intact
const PageError = ({ title, body, onRetry }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
    <section className="card" style={{ padding: 0 }}>
      <ErrorState
        title={title || "Couldn't load this page"}
        body={body || "A data source didn't respond. Your positions and identity are unchanged — this is a read-side issue."}
        technical={"Error: ConnectError: rpc_unavailable\n  at PageLoader.fetch (hooks/page.ts:51)"}
        onRetry={onRetry}
      />
    </section>
  </div>
);

Object.assign(window, {
  Skel, SkelRow, EmptyState, ErrorState, ToastStack, useToasts,
  PageHeaderSkel, KpiStripSkel, CardGridSkel, RowsSkel, PageSkeleton, PageError,
});
