// views_invitations.jsx — invitation-only signup management.
(function () {
  const { useEffect, useMemo, useState } = React;

  function canInvite(role) {
    return role === 'super_admin' || role === 'agency';
  }

  function statusTone(status) {
    if (status === 'accepted') return 'green';
    if (status === 'revoked' || status === 'expired') return 'coral';
    if (status === 'confirmed') return 'amber';
    return null;
  }

  function Invitations({ role }) {
    const allowed = canInvite(role);
    const [form, setForm] = useState({ name: '', email: '', role: 'client', organizationName: '', websiteUrl: '' });
    const [items, setItems] = useState([]);
    const [result, setResult] = useState(null);
    const [status, setStatus] = useState('');
    const [loading, setLoading] = useState(false);
    const roleOptions = useMemo(() => role === 'super_admin'
      ? [['client', 'Client'], ['agency', 'Agency'], ['super_admin', 'Super admin']]
      : [['client', 'Client']]
    , [role]);

    const load = async () => {
      if (!allowed) return;
      try {
        const data = await window.JS_API.invitations.list();
        setItems(data.invitations || []);
      } catch (e) {
        setStatus(e.message || 'Could not load invitations.');
      }
    };

    useEffect(() => { load(); }, [allowed]);

    const update = (key, value) => setForm(current => ({ ...current, [key]: value }));
    const create = async (event) => {
      event.preventDefault();
      setLoading(true);
      setStatus('Creating invitation...');
      setResult(null);
      try {
        const data = await window.JS_API.invitations.create(form);
        setResult(data);
        setStatus(data.mailDelivery?.ok === false
          ? 'Invitation created. Email is not configured, so share the URL and code manually.'
          : 'Invitation created.');
        setForm({ name: '', email: '', role: roleOptions[0][0], organizationName: '', websiteUrl: '' });
        await load();
      } catch (e) {
        setStatus(e.message || 'Could not create invitation.');
      } finally {
        setLoading(false);
      }
    };

    const revoke = async (id) => {
      setStatus('Revoking invitation...');
      try {
        await window.JS_API.invitations.revoke(id);
        await load();
        setStatus('Invitation revoked.');
      } catch (e) {
        setStatus(e.message || 'Could not revoke invitation.');
      }
    };

    if (!allowed) {
      return (
        <div className="js-view">
          <div className="js-pagehead"><div><p className="eyebrow">Access</p><h1>Invitations</h1>
            <p className="sub">Client users cannot invite accounts. Ask an agency or super-admin user to create an invitation.</p></div></div>
          <Panel><div className="js-gap sev-high" style={{ margin: 0 }}><h4><Icon name="shieldCheck" size={16} />Invitation authority required</h4><p style={{ margin: 0 }}>This panel is restricted to super-admin and agency roles.</p></div></Panel>
        </div>
      );
    }

    return (
      <div className="js-view js-view--wide">
        <div className="js-pagehead"><div><p className="eyebrow">Access control</p><h1>Invite-only <em>signup</em></h1>
          <p className="sub">Create a one-time invitation link and six-digit verification code. Email delivery is not configured in this build, so manual sharing is the release-safe fallback.</p></div>
          <div className="js-head-actions"><Btn kind="ghost" icon="refresh" sm onClick={load}>Refresh</Btn></div></div>

        <div className="js-cols-main">
          <Panel>
            <PanelHead eyebrow="Create" title="New invitation" desc="Only the selected invite role and scope will be accepted during signup." />
            <form onSubmit={create} className="form-grid">
              <div className="field"><label className="field-label">Invitee name</label><input className="input" value={form.name} onChange={e => update('name', e.target.value)} placeholder="Jordan Rivera" /></div>
              <div className="field"><label className="field-label">Invitee email</label><input className="input" type="email" value={form.email} onChange={e => update('email', e.target.value)} placeholder="you@company.com" required /></div>
              <div className="field"><label className="field-label">Role</label><select className="select" value={form.role} onChange={e => update('role', e.target.value)}>{roleOptions.map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></div>
              <div className="field"><label className="field-label">{form.role === 'agency' ? 'Agency name' : 'Organization name'}</label><input className="input" value={form.organizationName} onChange={e => update('organizationName', e.target.value)} placeholder="Company or agency" /></div>
              <div className="field" style={{ gridColumn: '1 / -1' }}><label className="field-label">Website</label><input className="input" value={form.websiteUrl} onChange={e => update('websiteUrl', e.target.value)} placeholder="https://example.com" /></div>
              <div className="row" style={{ justifyContent: 'space-between', gridColumn: '1 / -1' }}>
                <span className="rc-sub">{status}</span>
                <Btn icon="users" disabled={loading}>{loading ? 'Creating...' : 'Create invitation'}</Btn>
              </div>
            </form>
          </Panel>

          <Panel raised>
            <PanelHead eyebrow="Manual fallback" title="Share details" desc="The invite URL and verification code are shown only when created." />
            {result ? (
              <div className="js-rows">
                <div className="field"><label className="field-label">Invite URL</label><input className="input" readOnly value={result.inviteUrl || ''} onFocus={e => e.target.select()} /></div>
                <div className="field-row">
                  <div className="field"><label className="field-label">Email</label><input className="input" readOnly value={result.inviteEmail || ''} /></div>
                  <div className="field"><label className="field-label">Verification code</label><input className="input" readOnly value={result.verificationCode || ''} onFocus={e => e.target.select()} /></div>
                </div>
                <div className="js-gap sev-low" style={{ margin: 0 }}><h4><Icon name="shieldCheck" size={16} />Manual delivery</h4><p style={{ margin: 0 }}>{result.mailDelivery?.message || 'Share the URL and code out of band.'}</p></div>
              </div>
            ) : <p className="rc-sub" style={{ margin: 0 }}>Create an invitation to reveal a copyable URL and code.</p>}
          </Panel>
        </div>

        <Panel style={{ marginTop: 22 }}>
          <PanelHead eyebrow="History" title="Invitations" desc="Accepted links cannot be reused; revoked and expired invitations are rejected." />
          <div className="js-rows">
            {items.length ? items.map(invitation => (
              <div key={invitation.id} className="js-rowcard" style={{ gridTemplateColumns: '1fr auto auto' }}>
                <div><div className="rc-title">{invitation.name || invitation.email}</div><div className="rc-sub">{invitation.email} · {invitation.role} · expires {String(invitation.expiresAt || '').slice(0, 10)}</div></div>
                <Pill tone={statusTone(invitation.status)} dot={false}>{invitation.status}</Pill>
                {['pending', 'confirmed'].includes(invitation.status) ? <Btn sm kind="ghost" icon="x" onClick={() => revoke(invitation.id)}>Revoke</Btn> : <span className="rc-sub">Locked</span>}
              </div>
            )) : <div className="empty-state">No invitations yet.</div>}
          </div>
        </Panel>
      </div>
    );
  }

  window.Invitations = Invitations;
})();
