// Primate App Kit — Organization Settings
const { useState: useStateORG } = React;

// ---- section header with the gold accent bar ----
function OrgSection({ title, right, children }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 16, minWidth: 0 }}>
          <span style={{ width: 2, height: 28, background: "var(--gold)", flexShrink: 0 }} />
          <h2 style={{ font: "500 20px/28px var(--font-sans)", letterSpacing: "-0.45px", margin: 0, color: "var(--fg)" }}>{title}</h2>
        </div>
        {right}
      </div>
      {children}
    </div>
  );
}

// ---- filled field (text or select) ----
function OrgField({ label, value, select }) {
  const [hover, setHover] = useStateORG(false);
  const [focus, setFocus] = useStateORG(false);
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8, flex: 1, minWidth: 0 }}>
      <label style={{ font: "var(--t-label)", fontWeight: 400, color: "var(--fg)" }}>{label}</label>
      <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{ display: "flex", alignItems: "center", gap: 8, height: 48, boxSizing: "border-box", padding: "0 16px", borderRadius: "var(--r-md)", background: "var(--bg-elevated)", border: `1px solid ${focus ? "var(--gold-mid)" : hover ? "var(--border-hover)" : "var(--border-subtle)"}`, transition: "border-color .14s ease" }}>
        {select ? (
          <React.Fragment>
            <span style={{ flex: 1, font: "var(--t-body)", color: "var(--fg)" }}>{value}</span>
            <Icon name="chevron-down" size={18} color="var(--fg-placeholder)" />
          </React.Fragment>
        ) : (
          <input defaultValue={value} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
            style={{ flex: 1, minWidth: 0, background: "transparent", border: "none", outline: "none", color: "var(--fg)", font: "var(--t-body)" }} />
        )}
      </div>
    </div>
  );
}

// ---- compact search field ----
function OrgSearch({ placeholder, width }) {
  const [h, setH] = useStateORG(false);
  return (
    <div onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ display: "flex", alignItems: "center", gap: 8, height: 36, boxSizing: "border-box", padding: "0 14px", borderRadius: "var(--r-md)", background: "var(--bg-elevated)", border: `1px solid ${h ? "var(--border-hover)" : "var(--border-subtle)"}`, width, transition: "border-color .14s ease" }}>
      <Icon name="search" size={16} color="var(--fg-placeholder)" />
      <input placeholder={placeholder} style={{ flex: 1, minWidth: 0, background: "transparent", border: "none", outline: "none", color: "var(--fg)", font: "var(--t-body-sm)" }} />
    </div>
  );
}

// ---- "..." actions button ----
function ActionsBtn() {
  const [h, setH] = useStateORG(false);
  return (
    <button onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ width: 30, height: 28, display: "flex", alignItems: "center", justifyContent: "center", borderRadius: "var(--r-sm)", border: `1px solid ${h ? "var(--border-hover)" : "var(--border-subtle)"}`, background: h ? "var(--bg-elevated-2)" : "var(--bg-elevated)", color: "var(--fg-secondary)", cursor: "pointer", transition: "background .14s ease" }}>
      <Icon name="ellipsis" size={15} />
    </button>
  );
}

// ---- table (grid; fills parent on desktop, horizontally scrollable w/ full text on mobile) ----
function OrgTable({ cols, rows, mobile }) {
  const template = mobile
    ? cols.map(c => (c.mw || 120) + "px").join(" ")
    : cols.map(c => c.w).join(" ");
  const padX = mobile ? 16 : 24;
  const table = (
    <div style={{ width: mobile ? "max-content" : "auto", minWidth: mobile ? "100%" : 0, boxSizing: "border-box", borderRadius: mobile ? 0 : "var(--r-md)", border: mobile ? "none" : "1px solid var(--border)", background: "var(--bg-card)", overflow: "hidden" }}>
      <div style={{ display: "grid", gridTemplateColumns: template, alignItems: "center", gap: mobile ? 16 : 0, padding: `0 ${padX}px`, height: 48, background: "var(--bg-elevated)", borderBottom: "1px solid var(--border)", font: "var(--t-label)", color: "var(--fg-secondary)" }}>
        {cols.map(c => <span key={c.key} style={{ textAlign: c.key === "actions" ? "right" : "left", whiteSpace: "nowrap", overflow: mobile ? "visible" : "hidden", textOverflow: "ellipsis" }}>{c.label}</span>)}
      </div>
      {rows.map((r, i) => <OrgRow key={i} cols={cols} row={r} template={template} padX={padX} mobile={mobile} />)}
    </div>
  );
  if (mobile) return <div style={{ overflowX: "auto", overflowY: "hidden", WebkitOverflowScrolling: "touch", borderRadius: "var(--r-md)", border: "1px solid var(--border)" }}>{table}</div>;
  return table;
}

function OrgRow({ cols, row, template, padX = 24, mobile }) {
  const [h, setH] = useStateORG(false);
  return (
    <div onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ display: "grid", gridTemplateColumns: template, alignItems: "center", gap: mobile ? 16 : 0, padding: `0 ${padX}px`, height: 50, borderTop: "1px solid var(--border)", background: h ? "rgba(255,255,255,0.035)" : "transparent", transition: "background .1s ease" }}>
      {cols.map(c => c.key === "actions"
        ? <span key={c.key} style={{ display: "flex", justifyContent: "flex-end" }}><ActionsBtn /></span>
        : <span key={c.key} style={{ font: "var(--t-body-sm)", color: c.key === "name" ? "var(--fg)" : "var(--fg-secondary)", whiteSpace: "nowrap", overflow: mobile ? "visible" : "hidden", textOverflow: "ellipsis", paddingRight: mobile ? 0 : 10 }}>{row[c.key]}</span>
      )}
    </div>
  );
}

const ORG_INVITE_COLS = [
  { key: "email", label: "Email", w: "minmax(0,2fr)", mw: 210 },
  { key: "role", label: "Role", w: "minmax(0,1.2fr)", mw: 80 },
  { key: "expires", label: "Expires", w: "minmax(0,1.4fr)", mw: 120 },
  { key: "actions", label: "Actions", w: "100px", mw: 72 },
];
const ORG_INVITES = [
  { email: "conor@conorroberts.com", role: "Member", expires: "Mar 9, 11:37 PM" },
];

const ORG_MEMBER_COLS = [
  { key: "name", label: "Name", w: "minmax(0,1.4fr)", mw: 130 },
  { key: "email", label: "Email", w: "minmax(0,2fr)", mw: 230 },
  { key: "role", label: "Role", w: "minmax(0,1.2fr)", mw: 90 },
  { key: "actions", label: "Actions", w: "100px", mw: 72 },
];
const ORG_MEMBERS = [
  { name: "Jeremy Bell", email: "bell.jeremy.robert@gmail.com", role: "Admin" },
  { name: "Jack Ruttan", email: "jackjr.ruttan@gmail.com", role: "Member" },
];

function DeleteOrgCard({ mobile }) {
  const [h, setH] = useStateORG(false);
  return (
    <div style={{ display: "flex", flexDirection: mobile ? "column" : "row", alignItems: mobile ? "stretch" : "center", justifyContent: "space-between", gap: 16, borderRadius: "var(--r-md)", border: "1px solid var(--danger-border)", background: "rgba(239,68,68,0.10)", padding: 12 }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 6, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--danger)" }}>
          <Icon name="circle-alert" size={18} style={{ flexShrink: 0 }} />
          <span style={{ font: "500 18px/24px var(--font-sans)", color: "var(--danger)" }}>Delete Organization</span>
        </div>
        <span style={{ font: "var(--t-body-sm)", color: "var(--fg)" }}>You will not be able to recover this organization after it has been deleted.</span>
      </div>
      <button onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
        style={{ flexShrink: 0, alignSelf: mobile ? "stretch" : "auto", height: 40, padding: "0 18px", borderRadius: "var(--r-md)", border: "none", background: h ? "#b91c1c" : "#DC2626", color: "#fff", font: "var(--t-btn)", fontSize: 14, cursor: "pointer", transition: "background .14s ease", whiteSpace: "nowrap" }}>
        Delete Organization
      </button>
    </div>
  );
}

function SaveChangesBtn() {
  // disabled until a change is made (matches the design's inactive state)
  return (
    <button disabled style={{ height: 36, padding: "0 16px", borderRadius: "var(--r-md)", border: "1px solid var(--border-subtle)", background: "var(--bg-elevated)", color: "var(--fg-faint)", font: "400 14px var(--font-mono)", cursor: "not-allowed", opacity: 0.7, whiteSpace: "nowrap" }}>
      Save Changes
    </button>
  );
}

function InviteUserModal({ onClose, mobile }) {
  const [emailFocus, setEmailFocus] = useStateORG(false);
  const [hSend, setHSend] = useStateORG(false);
  const [hClose, setHClose] = useStateORG(false);
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 1000, overflow: "hidden", background: "rgba(0,0,0,0.46)", display: "flex", alignItems: mobile ? "flex-end" : "center", justifyContent: "center", padding: mobile ? 0 : 20 }}>
      <style>{`@keyframes orgSheetUp { from { transform: translateY(100%); } to { transform: translateY(0); } }`}</style>
      <div onClick={(e) => e.stopPropagation()} style={{ width: mobile ? "100%" : "min(514px, 100%)", borderRadius: mobile ? "16px 16px 0 0" : "var(--r-md)", background: "var(--bg-card)", border: "1px solid var(--border)", overflow: "hidden", boxShadow: "0 30px 90px rgba(0,0,0,0.55)", animation: mobile ? "orgSheetUp .26s cubic-bezier(0.32,0.72,0,1)" : "none" }}>
        {mobile && <div style={{ display: "flex", justifyContent: "center", paddingTop: 10 }}><span style={{ width: 36, height: 4, borderRadius: 999, background: "var(--border-hover)" }} /></div>}
        {/* header */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "24px", borderBottom: "1px solid var(--border)" }}>
          <span style={{ font: "700 20px/1 var(--font-sans)", color: "var(--fg)" }}>Invite User</span>
          <button onClick={onClose} onMouseEnter={() => setHClose(true)} onMouseLeave={() => setHClose(false)}
            style={{ width: 28, height: 28, display: "flex", alignItems: "center", justifyContent: "center", borderRadius: "var(--r-sm)", border: "none", background: hClose ? "var(--bg-elevated)" : "transparent", color: "var(--fg)", cursor: "pointer", transition: "background .14s ease" }}>
            <Icon name="x" size={18} color="var(--fg)" />
          </button>
        </div>
        {/* body */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16, padding: 24 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            <label style={{ font: "var(--t-label)", fontWeight: 400, color: "var(--fg)" }}>Email</label>
            <div style={{ height: 48, boxSizing: "border-box", padding: "0 16px", display: "flex", alignItems: "center", borderRadius: "var(--r-md)", background: "var(--bg-elevated)", border: `1px solid ${emailFocus ? "var(--gold-mid)" : "var(--border-subtle)"}`, transition: "border-color .14s ease" }}>
              <input placeholder="" onFocus={() => setEmailFocus(true)} onBlur={() => setEmailFocus(false)}
                style={{ flex: 1, minWidth: 0, background: "transparent", border: "none", outline: "none", color: "var(--fg)", font: "var(--t-body)" }} />
            </div>
          </div>
          <OrgField label="Role" value="Member" select />
        </div>
        {/* footer */}
        <div style={{ display: "flex", justifyContent: "flex-end", padding: "16px 24px", borderTop: "1px solid var(--border)" }}>
          <button onClick={onClose} onMouseEnter={() => setHSend(true)} onMouseLeave={() => setHSend(false)}
            style={{ height: 36, padding: "0 16px", borderRadius: "var(--r-md)", border: "none", background: hSend ? "var(--gold-bright)" : "var(--gold)", color: "var(--on-gold)", font: "400 14px var(--font-mono)", cursor: "pointer", transition: "background .14s ease", whiteSpace: "nowrap" }}>Send Invite</button>
        </div>
      </div>
    </div>
  );
}

function Organization() {
  const vp = useViewport();
  const mobile = vp === "mobile";
  const tablet = vp === "tablet";
  const [inviteOpen, setInviteOpen] = useStateORG(false);
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: mobile ? 32 : 48 }}>
        {/* page header */}
        <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
          <h1 style={{ font: mobile ? "600 24px/30px var(--font-sans)" : "600 30px/36px var(--font-sans)", letterSpacing: "0.4px", margin: 0, color: "var(--fg)" }}>Organization Settings</h1>
          <p style={{ font: "var(--t-body-sm)", color: "var(--fg-secondary)", margin: 0 }}>Manage your organization's details, members, and security settings.</p>
        </div>

        {/* organization details */}
        <OrgSection title="Organization Details" right={<SaveChangesBtn />}>
          <div style={{ display: "flex", flexDirection: mobile ? "column" : "row", gap: mobile ? 16 : 24 }}>
            <OrgField label="Organization Name" value="Acme Inc" />
            <OrgField label="My Role" value="Admin" select />
          </div>
        </OrgSection>

        {/* invites */}
        <OrgSection title="Invites" right={
          mobile ? (
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <Btn variant="primary" size="sm" style={{ height: 36 }} onClick={() => setInviteOpen(true)}>Invite User</Btn>
              <Btn variant="secondary" size="sm" style={{ height: 36 }}>Invite Link</Btn>
            </div>
          ) : (
            <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap", flex: "0 1 auto", justifyContent: "flex-end" }}>
              <OrgSearch placeholder="Search invites..." width={tablet ? 200 : 300} />
              <Btn variant="primary" size="sm" style={{ height: 36 }} onClick={() => setInviteOpen(true)}>Invite User</Btn>
              <Btn variant="secondary" size="sm" style={{ height: 36 }}>Invite Link</Btn>
            </div>
          )
        }>
          {mobile && <OrgSearch placeholder="Search invites..." width="100%" />}
          <OrgTable cols={ORG_INVITE_COLS} rows={ORG_INVITES} mobile={mobile} />
        </OrgSection>

        {/* members */}
        <OrgSection title="Members" right={
          <OrgSearch placeholder="Search members..." width={mobile ? "100%" : tablet ? 220 : 340} />
        }>
          <OrgTable cols={ORG_MEMBER_COLS} rows={ORG_MEMBERS} mobile={mobile} />
        </OrgSection>

        {/* danger zone */}
        <DeleteOrgCard mobile={mobile} />
        {inviteOpen && <InviteUserModal mobile={mobile} onClose={() => setInviteOpen(false)} />}
    </div>
  );
}

Object.assign(window, { Organization });
