/* Matter Protocol — modal infrastructure
 *
 * Exposes a global window.matterUI registered by <ModalHost /> mounted at App root:
 *   window.matterUI.openAccess()
 *   window.matterUI.openNotice(key)   // 'github' | 'telegram' | 'twitter' | 'changelog' | 'sdk' | 'examples' | 'tutorials' | 'docsSection'
 *   window.matterUI.close()
 *
 * Buttons across the page call these in onClick. Safe to call before mount — guarded with ?.
 */

function ModalHost() {
  const t = window.matterTokens;
  const [modal, setModal] = React.useState(null); // null | 'access' | { kind: 'notice', key }
  const [submitted, setSubmitted] = React.useState(false);

  React.useEffect(() => {
    window.matterUI = {
      openAccess: () => { setSubmitted(false); setModal('access'); },
      openNotice: (key) => setModal({ kind: 'notice', key }),
      close: () => setModal(null),
    };
    return () => { window.matterUI = undefined; };
  }, []);

  // Lock body scroll while modal open
  React.useEffect(() => {
    if (modal) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = prev; };
    }
  }, [modal]);

  // ESC to close
  React.useEffect(() => {
    if (!modal) return;
    const onKey = (e) => { if (e.key === 'Escape') setModal(null); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [modal]);

  if (!modal) return null;

  return (
    <ModalShell onClose={() => setModal(null)}>
      {modal === 'access' && (
        submitted
          ? <AccessSuccess onClose={() => setModal(null)} />
          : <AccessForm onSubmit={() => setSubmitted(true)} />
      )}
      {modal && modal.kind === 'notice' && (
        <NoticeBody k={modal.key} onClose={() => setModal(null)} />
      )}
    </ModalShell>
  );
}

function ModalShell({ children, onClose }) {
  const t = window.matterTokens;
  return (
    <div
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{
        position: 'fixed', inset: 0,
        background: 'rgba(20,19,15,0.42)',
        backdropFilter: 'blur(4px)',
        WebkitBackdropFilter: 'blur(4px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 24,
        zIndex: 9999,
        animation: 'matterFadeIn 180ms ease',
      }}>
      <style>{`
        @keyframes matterFadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes matterSlideIn { from { opacity: 0; transform: translateY(8px) scale(0.99); } to { opacity: 1; transform: translateY(0) scale(1); } }
      `}</style>
      <div style={{
        background: t.paper,
        border: `1px solid ${t.line}`,
        borderRadius: 16,
        boxShadow: `0 20px 60px -20px rgba(20,19,15,0.4), 0 1px 0 ${t.line}`,
        width: '100%',
        maxWidth: 560,
        maxHeight: 'calc(100vh - 48px)',
        overflowY: 'auto',
        position: 'relative',
        animation: 'matterSlideIn 200ms cubic-bezier(0.16, 1, 0.3, 1)',
      }}>
        <button onClick={onClose} aria-label="close" style={{
          position: 'absolute', top: 16, right: 16,
          width: 30, height: 30,
          background: 'transparent',
          border: `1px solid ${t.line2}`,
          borderRadius: 8,
          color: t.muted,
          cursor: 'pointer',
          fontSize: 16,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'inherit',
          lineHeight: 1,
          zIndex: 2,
        }}
        onMouseEnter={(e) => { e.currentTarget.style.borderColor = t.line3; e.currentTarget.style.color = t.ink; }}
        onMouseLeave={(e) => { e.currentTarget.style.borderColor = t.line2; e.currentTarget.style.color = t.muted; }}
        >×</button>
        {children}
      </div>
    </div>
  );
}

function ModalHeader({ eyebrow, title, sub }) {
  const t = window.matterTokens;
  return (
    <div style={{ padding: '32px 36px 24px', borderBottom: `1px solid ${t.line}` }}>
      <div style={{
        display: 'inline-flex', alignItems: 'center', gap: 9,
        fontFamily: "'Geist Mono', monospace",
        fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.12em',
        color: t.muted,
        marginBottom: 14,
      }}>
        <MatterMark size={14} />
        {eyebrow}
      </div>
      <h2 style={{
        margin: 0,
        fontSize: 26,
        lineHeight: 1.12,
        letterSpacing: '-0.02em',
        fontWeight: 500,
        color: t.ink,
        textTransform: 'lowercase',
      }}>{title}</h2>
      {sub && <p style={{
        margin: '8px 0 0',
        fontSize: 14.5, lineHeight: 1.5,
        color: t.muted,
      }}>{sub}</p>}
    </div>
  );
}

/* ── ACCESS FORM ──────────────────────────── */

function AccessForm({ onSubmit }) {
  const t = window.matterTokens;
  const [form, setForm] = React.useState({
    email: '',
    handle: '',
    handleKind: 'tg',
    background: '',
    capital: '',
    building: '',
  });

  const focusOptions = [
    { key: 'solo',    label: 'solo / independent' },
    { key: 'fund',    label: 'quant fund' },
    { key: 'mm',      label: 'market maker' },
    { key: 'agent',   label: 'agent team' },
    { key: 'other',   label: 'other' },
  ];
  const capitalOptions = [
    { key: '<50k',    label: '< $50k' },
    { key: '50-500',  label: '$50k–$500k' },
    { key: '500-5m',  label: '$500k–$5M' },
    { key: '5m+',     label: '$5M+' },
    { key: 'lp',      label: 'LP capital' },
  ];

  const canSubmit =
    form.email.includes('@') &&
    form.handle.trim().length > 0 &&
    form.background &&
    form.building.trim().length > 6;

  const submit = (e) => {
    e.preventDefault();
    if (!canSubmit) return;
    // form is local-only; in production this would POST somewhere
    onSubmit(form);
  };

  return (
    <form onSubmit={submit}>
      <ModalHeader
        eyebrow="request access"
        title="join the private alpha."
        sub="we read every one. tell us who you are and what you'd build first — we'll come back by email."
      />

      <div style={{ padding: '24px 36px 28px', display: 'flex', flexDirection: 'column', gap: 22 }}>

        <Field label="email" hint="we'll respond here">
          <input
            type="email"
            value={form.email}
            onChange={(e) => setForm({ ...form, email: e.target.value })}
            placeholder="you@domain.xyz"
            style={inputStyle()}
          />
        </Field>

        <Field label="handle" hint="so we can poke around your past work">
          <div style={{
            display: 'grid',
            gridTemplateColumns: '120px 1fr',
            gap: 8,
          }}>
            <select
              value={form.handleKind}
              onChange={(e) => setForm({ ...form, handleKind: e.target.value })}
              style={{ ...inputStyle(), paddingRight: 8, cursor: 'pointer', appearance: 'none', backgroundImage: `linear-gradient(45deg, transparent 50%, ${t.muted} 50%), linear-gradient(135deg, ${t.muted} 50%, transparent 50%)`, backgroundPosition: 'calc(100% - 16px) 14px, calc(100% - 12px) 14px', backgroundSize: '4px 4px, 4px 4px', backgroundRepeat: 'no-repeat' }}
            >
              <option value="tg">telegram</option>
              <option value="x">x / twitter</option>
              <option value="gh">github</option>
            </select>
            <input
              type="text"
              value={form.handle}
              onChange={(e) => setForm({ ...form, handle: e.target.value })}
              placeholder="@yourhandle"
              style={inputStyle()}
            />
          </div>
        </Field>

        <Field label="background" hint="closest fit — pick one">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {focusOptions.map(o => (
              <Chip
                key={o.key}
                active={form.background === o.key}
                onClick={() => setForm({ ...form, background: o.key })}
              >{o.label}</Chip>
            ))}
          </div>
        </Field>

        <Field label="capital you'd deploy" hint="rough estimate · optional, but useful">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {capitalOptions.map(o => (
              <Chip
                key={o.key}
                active={form.capital === o.key}
                onClick={() => setForm({ ...form, capital: o.key === form.capital ? '' : o.key })}
              >{o.label}</Chip>
            ))}
          </div>
        </Field>

        <Field label="what would you build first?" hint="be specific. one paragraph is plenty.">
          <textarea
            value={form.building}
            onChange={(e) => setForm({ ...form, building: e.target.value })}
            placeholder="e.g. funding-rate carry on top 5 perp venues with a vol-targeted sizer and a hard drawdown cap. starting on eth/sol, expanding from there."
            rows={4}
            style={{ ...inputStyle(), resize: 'vertical', lineHeight: 1.5, fontFamily: 'inherit' }}
          />
        </Field>

      </div>

      <div style={{
        padding: '18px 36px 28px',
        borderTop: `1px solid ${t.line}`,
        background: t.surface,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        gap: 16,
        borderBottomLeftRadius: 16,
        borderBottomRightRadius: 16,
      }}>
        <div style={{
          fontFamily: "'Geist Mono', monospace",
          fontSize: 11,
          color: t.muted,
        }}>
          reviewed by hand · 1–3 business days
        </div>
        <button
          type="submit"
          disabled={!canSubmit}
          style={{
            background: canSubmit ? t.ink : t.line,
            color: canSubmit ? t.bg : t.muted,
            border: 'none',
            padding: '12px 22px',
            borderRadius: 10,
            fontSize: 14.5,
            fontWeight: 500,
            cursor: canSubmit ? 'pointer' : 'not-allowed',
            letterSpacing: '-0.005em',
            fontFamily: 'inherit',
            display: 'inline-flex', alignItems: 'center', gap: 8,
            transition: 'all 0.15s ease',
          }}
        >
          send request
          <span style={{ opacity: 0.6 }}>→</span>
        </button>
      </div>
    </form>
  );
}

function AccessSuccess({ onClose }) {
  const t = window.matterTokens;
  return (
    <div style={{ padding: '52px 44px 44px', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18 }}>
      <div style={{
        width: 64, height: 64, borderRadius: '50%',
        background: t.limeWash,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        position: 'relative',
      }}>
        <div style={{
          width: 36, height: 36,
          display: 'grid', gridTemplateColumns: '1fr 1fr', gridTemplateRows: '1fr 1fr', gap: 3,
        }}>
          <span style={{ background: t.limeDeep, borderRadius: 2 }} />
          <span style={{ background: t.limeDeep, borderRadius: 2 }} />
          <span style={{ background: t.ink, borderRadius: 2 }} />
          <span style={{ background: t.limeDeep, borderRadius: 2 }} />
        </div>
      </div>
      <div style={{
        fontFamily: "'Geist Mono', monospace",
        fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.12em',
        color: t.muted,
      }}>request received</div>
      <h2 style={{
        margin: 0,
        fontSize: 30,
        lineHeight: 1.1,
        letterSpacing: '-0.022em',
        fontWeight: 500,
        color: t.ink,
        textTransform: 'lowercase',
        maxWidth: 360,
      }}>thanks. we'll be in touch.</h2>
      <p style={{
        margin: 0,
        fontSize: 15,
        lineHeight: 1.55,
        color: t.muted,
        maxWidth: 420,
      }}>we read every request by hand. expect a reply from <span style={{ color: t.ink, fontFamily: "'Geist Mono', monospace", fontSize: 13.5 }}>hello@matterprotocol.xyz</span> within 1–3 business days. if it's been longer, ping us.</p>

      <div style={{
        marginTop: 18,
        padding: 14,
        background: t.surface,
        border: `1px solid ${t.line}`,
        borderRadius: 10,
        fontFamily: "'Geist Mono', monospace",
        fontSize: 12,
        color: t.muted,
        maxWidth: 380,
        textAlign: 'left',
        lineHeight: 1.6,
      }}>
        <div style={{ color: t.ink2, marginBottom: 4 }}>// while you wait</div>
        <div>· skim the <a href="docs.html" style={{ color: t.ink, textDecoration: 'underline', textDecorationColor: t.line2 }}>docs</a></div>
        <div>· try the composer above</div>
        <div>· tell a friend</div>
      </div>

      <button
        onClick={onClose}
        style={{
          marginTop: 8,
          background: 'transparent',
          color: t.ink2,
          border: `1px solid ${t.line2}`,
          padding: '10px 18px',
          borderRadius: 10,
          fontSize: 14,
          fontWeight: 500,
          cursor: 'pointer',
          letterSpacing: '-0.005em',
          fontFamily: 'inherit',
        }}
      >back to the page</button>
    </div>
  );
}

/* ── NOTICE MODAL ─────────────────────────── */

const NOTICES = {
  github: {
    eyebrow: 'github',
    title: 'the repo is private right now.',
    body: 'matter is in private alpha — the sdk lives in a closed repository while we stabilize the primitive interface. once we open up (q1 2027, alongside the public composer), the org goes live and pull requests open.',
    cta: 'request alpha access',
    ctaAction: 'access',
    secondary: 'view the public roadmap',
    secondaryAction: 'closeAndScroll',
    secondaryTarget: '#roadmap-section',
    tag: '@matter-protocol',
    icon: 'gh',
  },
  telegram: {
    eyebrow: 'telegram',
    title: 'no public channel yet.',
    body: 'we run a private telegram for alpha builders only — that\'s where the direct line to the team lives. request access and you\'ll get the invite in your acceptance email.',
    cta: 'request alpha access',
    ctaAction: 'access',
    icon: 'tg',
  },
  twitter: {
    eyebrow: 'twitter / x',
    title: '@matterprotocol — soon.',
    body: 'the account exists but we\'re not posting until the public composer ships. for now, follow along here. for direct conversations, the alpha telegram is where everything happens.',
    cta: 'request alpha access',
    ctaAction: 'access',
    icon: 'tw',
  },
  changelog: {
    eyebrow: 'changelog',
    title: 'no public changelog yet.',
    body: 'we ship daily but version notes go to alpha participants over telegram, not a public feed. once the sdk hits v1 we\'ll start a proper changelog at /changelog.',
    cta: 'request alpha access',
    ctaAction: 'access',
    icon: 'cl',
  },
  sdk: {
    eyebrow: 'sdk',
    title: 'sdk reference lives in the docs.',
    body: 'the public-facing sdk surface — types, exports, examples — is on the docs page. for the actual package, access is granted with alpha acceptance.',
    cta: 'open docs',
    ctaAction: 'docs',
    icon: 'dc',
  },
  tutorials: {
    eyebrow: 'tutorials',
    title: 'we publish tutorials inside the docs.',
    body: 'every primitive ships with a worked example. the quickstart walks you through composing your first strategy in five lines. more tutorials land alongside each major release.',
    cta: 'open docs',
    ctaAction: 'docs',
    icon: 'dc',
  },
  examples: {
    eyebrow: 'examples',
    title: 'example strategies are in the docs.',
    body: 'we\'ve included three reference strategies — a basis trade, a vol-targeted trend follow, and a funding-rate carry — fully composed from primitives. read through the docs to see them.',
    cta: 'open docs',
    ctaAction: 'docs',
    icon: 'dc',
  },
};

function NoticeBody({ k, onClose }) {
  const t = window.matterTokens;
  const n = NOTICES[k];
  if (!n) return null;

  const handleCta = () => {
    onClose();
    if (n.ctaAction === 'access') {
      setTimeout(() => window.matterUI?.openAccess?.(), 60);
    } else if (n.ctaAction === 'docs') {
      window.location.href = 'docs.html';
    }
  };

  return (
    <div>
      <ModalHeader eyebrow={n.eyebrow} title={n.title} />
      <div style={{ padding: '24px 36px 18px' }}>
        <p style={{ margin: 0, fontSize: 15, lineHeight: 1.6, color: t.ink2 }}>{n.body}</p>

        {n.tag && (
          <div style={{
            marginTop: 20,
            padding: '14px 16px',
            background: t.bg,
            border: `1px solid ${t.line}`,
            borderRadius: 10,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            fontFamily: "'Geist Mono', monospace",
            fontSize: 13,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{
                width: 8, height: 8, borderRadius: '50%',
                background: t.soft,
              }} />
              <span style={{ color: t.muted }}>github.com/</span>
              <span style={{ color: t.ink }}>{n.tag}</span>
            </div>
            <span style={{
              fontSize: 10.5,
              textTransform: 'uppercase',
              letterSpacing: '0.1em',
              color: t.muted,
              padding: '3px 7px',
              border: `1px solid ${t.line2}`,
              borderRadius: 4,
            }}>private</span>
          </div>
        )}
      </div>

      <div style={{
        padding: '18px 36px 26px',
        borderTop: `1px solid ${t.line}`,
        background: t.surface,
        display: 'flex',
        justifyContent: 'flex-end',
        gap: 10,
        borderBottomLeftRadius: 16,
        borderBottomRightRadius: 16,
      }}>
        <button onClick={onClose} style={{
          background: 'transparent', color: t.ink2,
          border: `1px solid ${t.line2}`,
          padding: '11px 16px', borderRadius: 10, fontSize: 14, fontWeight: 500,
          cursor: 'pointer', letterSpacing: '-0.005em', fontFamily: 'inherit',
        }}>close</button>
        <button onClick={handleCta} style={{
          background: t.ink, color: t.bg, border: 'none',
          padding: '11px 18px', borderRadius: 10, fontSize: 14, fontWeight: 500,
          cursor: 'pointer', letterSpacing: '-0.005em', fontFamily: 'inherit',
          display: 'inline-flex', alignItems: 'center', gap: 8,
        }}>
          {n.cta}
          <span style={{ opacity: 0.6 }}>→</span>
        </button>
      </div>
    </div>
  );
}

/* ── small atoms ──────────────────────────── */

function Field({ label, hint, children }) {
  const t = window.matterTokens;
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12 }}>
        <span style={{
          fontFamily: "'Geist Mono', monospace",
          fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em',
          color: t.ink2,
        }}>{label}</span>
        {hint && <span style={{
          fontSize: 11.5, color: t.muted,
        }}>{hint}</span>}
      </div>
      {children}
    </label>
  );
}

function Chip({ active, onClick, children }) {
  const t = window.matterTokens;
  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        background: active ? t.ink : t.paper,
        color: active ? t.bg : t.ink2,
        border: `1px solid ${active ? t.ink : t.line2}`,
        padding: '7px 12px',
        borderRadius: 999,
        fontSize: 13,
        fontWeight: 500,
        cursor: 'pointer',
        letterSpacing: '-0.005em',
        fontFamily: 'inherit',
        transition: 'all 0.12s ease',
      }}
      onMouseEnter={(e) => { if (!active) e.currentTarget.style.borderColor = t.line3; }}
      onMouseLeave={(e) => { if (!active) e.currentTarget.style.borderColor = t.line2; }}
    >{children}</button>
  );
}

function inputStyle() {
  const t = window.matterTokens;
  return {
    width: '100%',
    background: t.surface,
    border: `1px solid ${t.line2}`,
    borderRadius: 10,
    padding: '11px 14px',
    fontSize: 14.5,
    color: t.ink,
    fontFamily: 'inherit',
    letterSpacing: '-0.005em',
    outline: 'none',
    transition: 'border-color 0.15s ease, box-shadow 0.15s ease',
    boxSizing: 'border-box',
  };
}

// Global focus style for inputs inside modals
(() => {
  if (typeof document === 'undefined') return;
  if (document.getElementById('matter-modal-focus-style')) return;
  const s = document.createElement('style');
  s.id = 'matter-modal-focus-style';
  s.textContent = `
    input:focus, textarea:focus, select:focus {
      border-color: #14130F !important;
      box-shadow: 0 0 0 3px rgba(200, 238, 44, 0.25);
    }
    input::placeholder, textarea::placeholder { color: #98948B; }
  `;
  document.head.appendChild(s);
})();

Object.assign(window, { ModalHost });
