/* ShareReportModal — centered dialog, design matches uploaded reference.
   Used by: Reports list bulk-action Share, Report Center header Share. */

const teamAvatars = [
  { initial: 'S', color: '#f59e0b' },
  { initial: 'J', color: '#8b5cf6' },
  { initial: 'M', color: '#ef4444' },
];

const AvatarStack = ({ avatars = teamAvatars, extra = 6 }) => (
  <div style={{ display: 'inline-flex', alignItems: 'center' }}>
    {avatars.map((a, i) => (
      <span key={i} style={{
        width: 22, height: 22, borderRadius: 9999,
        background: a.color, color: '#fff',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 10, fontWeight: 600,
        border: '2px solid var(--rc-card)',
        marginLeft: i === 0 ? 0 : -6,
      }}>{a.initial}</span>
    ))}
    {extra > 0 && (
      <span style={{
        marginLeft: -6, padding: '0 6px', height: 22, minWidth: 22,
        borderRadius: 9999, background: 'var(--rc-chip-bg)',
        border: '2px solid var(--rc-card)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 10, fontWeight: 600, color: 'var(--rc-text-sub)',
      }}>+{extra}</span>
    )}
  </div>
);

const ShareRow = ({ icon, iconBg, title, subtitle, right, onClick }) => (
  <button onClick={onClick} style={{
    display: 'flex', alignItems: 'center', gap: 14, width: '100%',
    padding: '13px 16px', borderRadius: 10, border: '1px solid var(--rc-border)',
    background: 'var(--rc-card)', cursor: 'pointer', fontFamily: 'inherit',
    textAlign: 'left', transition: 'background 120ms',
  }}
  onMouseEnter={e => e.currentTarget.style.background = 'var(--rc-hover)'}
  onMouseLeave={e => e.currentTarget.style.background = 'var(--rc-card)'}>
    <span style={{
      width: 34, height: 34, borderRadius: 9999, flexShrink: 0,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      background: iconBg || 'var(--rc-chip-bg)', color: 'var(--rc-text-sub)',
    }}>{icon}</span>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--rc-text)', lineHeight: 1.3 }}>{title}</div>
      {subtitle && <div style={{ fontSize: 12, color: 'var(--rc-text-sub)', marginTop: 2 }}>{subtitle}</div>}
    </div>
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
      {right}
      <Icon name="chevronRight" size={14} color="var(--rc-text-sub)" strokeWidth={2} />
    </div>
  </button>
);

const RoleDropdown = ({ value, onChange }) => {
  const [open, setOpen] = React.useState(false);
  /* RC-RPT-025 — invite roles are Editor/Viewer only (Owner is assigned, not invited) */
  const opts = ['Viewer', 'Editor'];
  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => setOpen(!open)} style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        padding: '9px 14px', borderRadius: 8,
        border: '1px solid var(--rc-border)', background: 'var(--rc-card)',
        color: 'var(--rc-text)', fontSize: 13, fontWeight: 500,
        cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap',
      }}>
        {value}
        <Icon name="chevronDown" size={12} color="var(--rc-text-sub)" />
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
          <div style={{
            position: 'absolute', top: 'calc(100% + 4px)', right: 0, zIndex: 41,
            background: 'var(--rc-card)', border: '1px solid var(--rc-border)',
            borderRadius: 8, boxShadow: '0 12px 32px -8px rgba(15,23,42,0.22)',
            minWidth: 140, padding: 4,
          }}>
            {opts.map(o => (
              <button key={o} onClick={() => { onChange(o); setOpen(false); }} style={{
                display: 'flex', alignItems: 'center', gap: 8, width: '100%',
                padding: '8px 10px', border: 0, borderRadius: 5, textAlign: 'left',
                background: o === value ? 'var(--rc-hover)' : 'transparent',
                cursor: 'pointer', fontFamily: 'inherit', fontSize: 12,
                color: 'var(--rc-text)', fontWeight: o === value ? 600 : 500,
              }}>
                <span style={{ width: 14, display: 'inline-flex', justifyContent: 'center' }}>
                  {o === value && <Icon name="check" size={11} color="var(--rc-green-ink)" strokeWidth={2.5} />}
                </span>
                {o}
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
};

const ShareReportModal = ({ open, onClose, title = 'Share Report', subjectCount }) => {
  const [emails, setEmails] = React.useState('');
  const [role, setRole] = React.useState('Viewer');
  const [passwordSet, setPasswordSet] = React.useState(false);
  const [pwdModal, setPwdModal] = React.useState(false);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <>
    <div style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(15, 23, 42, 0.45)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24,
    }}
    onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 620,
        background: 'var(--rc-card)', borderRadius: 14,
        boxShadow: '0 24px 60px -12px rgba(15,23,42,0.35)',
        overflow: 'hidden', fontFamily: 'Inter',
        maxHeight: '90vh', display: 'flex', flexDirection: 'column',
      }}>
        {/* Header */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '18px 20px', borderBottom: '1px solid var(--rc-border)',
        }}>
          <div>
            <h2 style={{
              margin: 0, fontFamily: 'Poppins', fontSize: 17, fontWeight: 700,
              color: 'var(--rc-text)', letterSpacing: '-0.01em',
            }}>{title}</h2>
            {subjectCount && (
              <div style={{ fontSize: 12, color: 'var(--rc-text-sub)', marginTop: 3 }}>
                {subjectCount} report{subjectCount === 1 ? '' : 's'} selected
              </div>
            )}
          </div>
          <button onClick={onClose} style={{
            width: 28, height: 28, border: 0, borderRadius: 6, background: 'transparent',
            cursor: 'pointer', color: 'var(--rc-text-sub)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="x" size={16} strokeWidth={2} />
          </button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflow: 'auto', padding: 20 }}>
          {/* Invite row */}
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--rc-text)', marginBottom: 8 }}>
            Add comma separated emails to invite
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'stretch' }}>
            <input
              value={emails}
              onChange={e => setEmails(e.target.value)}
              placeholder="email1@example.com, email2@example.com"
              style={{
                flex: 1, minWidth: 0,
                padding: '10px 14px', borderRadius: 8,
                border: '1px solid var(--rc-border)',
                background: 'var(--rc-card)', color: 'var(--rc-text)',
                fontSize: 13, fontFamily: 'inherit',
                outline: 'none',
              }}
              onFocus={e => e.target.style.borderColor = 'var(--rc-green)'}
              onBlur={e => e.target.style.borderColor = 'var(--rc-border)'}
            />
            <RoleDropdown value={role} onChange={setRole} />
            <button
              disabled={!emails.trim()}
              onClick={() => { setEmails(''); }}
              style={{
                padding: '9px 18px', borderRadius: 9999, border: 0, cursor: emails.trim() ? 'pointer' : 'not-allowed',
                background: emails.trim() ? 'var(--rc-green)' : 'color-mix(in srgb, var(--rc-green) 45%, transparent)',
                color: '#fff', fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
                whiteSpace: 'nowrap',
              }}>
              Invite
            </button>
          </div>

          {/* Who has access */}
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--rc-text)', marginTop: 22, marginBottom: 10 }}>
            Who has access
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <ShareRow
              icon={<Icon name="lock" size={15} />}
              iconBg={passwordSet ? 'color-mix(in srgb, var(--rc-amber, #f59e0b) 18%, transparent)' : undefined}
              title="Password Protection"
              subtitle={passwordSet ? 'Password required to access' : 'Require password to access'}
              right={passwordSet && (
                <>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      /* RC-SHARE-002 — open viewer challenge preview in new tab */
                      const u = new URL(window.location.href);
                      u.searchParams.set('locked', '1');
                      window.open(u.toString(), '_blank', 'noopener');
                    }}
                    title="Preview the viewer password screen"
                    style={{
                      padding: '3px 10px', borderRadius: 9999,
                      border: '1px solid var(--rc-border)',
                      background: 'var(--rc-card)', color: 'var(--rc-text-sub)',
                      fontSize: 11, fontWeight: 500, cursor: 'pointer',
                      fontFamily: 'inherit',
                      display: 'inline-flex', alignItems: 'center', gap: 5,
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = 'var(--rc-hover)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'var(--rc-card)'}>
                    <Icon name="external" size={10} />
                    Preview
                  </button>
                  <span style={{
                    padding: '3px 10px', borderRadius: 9999,
                    border: '1px solid color-mix(in srgb, var(--rc-amber, #f59e0b) 35%, transparent)',
                    background: 'color-mix(in srgb, var(--rc-amber, #f59e0b) 10%, transparent)',
                    color: 'var(--rc-amber, #b45309)',
                    fontSize: 11, fontWeight: 600,
                  }}>Protected</span>
                </>
              )}
              onClick={() => setPwdModal(true)}
            />
            <ShareRow
              icon={<svg width="17" height="17" viewBox="0 0 16 16" fill="none"><path d="M2 5a2 2 0 012-2h3l1.5 1.5H12a2 2 0 012 2v4.5a2 2 0 01-2 2H4a2 2 0 01-2-2V5z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/></svg>}
              title="Your Team"
              subtitle="9 people"
              right={
                <>
                  <span style={{
                    padding: '3px 10px', borderRadius: 9999,
                    border: '1px solid var(--rc-border)',
                    background: 'var(--rc-chip-bg)', color: 'var(--rc-text)',
                    fontSize: 11, fontWeight: 500,
                  }}>Viewer</span>
                  <AvatarStack extra={6} />
                  <Icon name="lock" size={14} color="var(--rc-text-sub)" />
                </>
              }
            />
            <ShareRow
              icon={<span style={{
                width: '100%', height: '100%', borderRadius: 9999,
                background: '#fbbf24', color: '#7c2d12',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 14, fontWeight: 700,
              }}>Y</span>}
              iconBg="transparent"
              title={<span>You <span style={{ color: 'var(--rc-text-sub)', fontWeight: 400, fontSize: 13 }}>(you)</span></span>}
              subtitle="timurtek.bizel@mixshift.io"
              right={
                <span style={{
                  padding: '4px 12px', borderRadius: 9999,
                  background: 'var(--rc-green)', color: '#fff',
                  fontSize: 11, fontWeight: 600,
                }}>Owner</span>
              }
            />
            <ShareRow
              icon={<svg width="17" height="17" viewBox="0 0 16 16" fill="none"><g stroke="currentColor" strokeWidth="1.4"><circle cx="5" cy="6" r="2"/><circle cx="11" cy="6" r="2"/><path d="M2 13c0-2 1.5-3 3-3s3 1 3 3M8 13c0-2 1.5-3 3-3s3 1 3 3" strokeLinecap="round"/></g></svg>}
              title="Shared"
              subtitle="9 people"
              right={<AvatarStack extra={5} />}
            />
          </div>
        </div>

        {/* Footer */}
        <div style={{
          padding: '14px 20px', borderTop: '1px solid var(--rc-border)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <button style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '8px 14px', borderRadius: 9999,
            border: '1px solid var(--rc-border)', background: 'var(--rc-card)',
            color: 'var(--rc-text)', fontSize: 12, fontWeight: 500,
            cursor: 'pointer', fontFamily: 'inherit',
          }}>
            <svg width="13" height="13" viewBox="0 0 16 16" fill="none"><path d="M6 10a3 3 0 004.24 0l2.83-2.83a3 3 0 10-4.24-4.24L7.83 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/><path d="M10 6a3 3 0 00-4.24 0L2.93 8.83a3 3 0 004.24 4.24L8.17 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
            Copy link
          </button>
        </div>
      </div>
    </div>
    {/* RC-RPT-022 — password protection sub-modal */}
    <PasswordProtectionModal
      open={pwdModal}
      hasPassword={passwordSet}
      onClose={() => setPwdModal(false)}
      onSet={() => setPasswordSet(true)}
      onRemove={() => setPasswordSet(false)}
    />
    </>
  );
};

Object.assign(window, { ShareReportModal });
