// Certs.jsx — certification verification system for the account dashboard.
// Verify cyber certs (Credly, HTB, manual) to earn points toward rank progression.
// SECURITY: all verification done server-side. No trust of client-provided cert data.

const LEVEL_STYLES = {
  entry:        { border: '#00E5FF', label: 'ENTRY',        bg: 'rgba(0,229,255,0.08)' },
  intermediate: { border: '#00FF41', label: 'INTERMEDIATE', bg: 'rgba(0,255,65,0.08)' },
  advanced:     { border: '#FFD23F', label: 'ADVANCED',     bg: 'rgba(255,210,63,0.08)' },
  elite:        { border: '#FF3344', label: 'ELITE',        bg: 'rgba(255,51,68,0.08)' },
};

const TABS = [
  { id: 'credly', label: 'CREDLY' },
  { id: 'htb',    label: 'HACK THE BOX' },
  { id: 'manual', label: 'MANUAL' },
];

const HTB_RANKS = [
  'Script Kiddie',
  'Hacker',
  'Pro Hacker',
  'Elite Hacker',
  'Guru',
  'Omniscient',
];

const getLevelStyle = (level) => LEVEL_STYLES[level] || LEVEL_STYLES.entry;

const Certs = () => {
  const [providers, setProviders] = React.useState([]);
  const [myCerts, setMyCerts] = React.useState([]);
  const [totalPoints, setTotalPoints] = React.useState(0);
  const [activeTab, setActiveTab] = React.useState('credly');
  const [verifying, setVerifying] = React.useState(false);
  const [result, setResult] = React.useState(null);
  const [badgeUrl, setBadgeUrl] = React.useState('');
  const [profileUrl, setProfileUrl] = React.useState('');
  const [claimedRank, setClaimedRank] = React.useState(HTB_RANKS[0]);
  const [selectedCertType, setSelectedCertType] = React.useState('');
  const [manualUrl, setManualUrl] = React.useState('');
  const [showCatalog, setShowCatalog] = React.useState(false);
  const [loading, setLoading] = React.useState(true);

  const loadData = async () => {
    try {
      const [provRes, certRes] = await Promise.all([
        window.OBC_API.getCertProviders(),
        window.OBC_API.getMyCerts(),
      ]);
      if (provRes && provRes.providers) setProviders(provRes.providers);
      if (certRes) {
        setMyCerts(certRes.certs || []);
        setTotalPoints(certRes.total_cert_points || 0);
      }
    } catch (e) {
      // silent — data will show empty states
    }
    setLoading(false);
  };

  React.useEffect(() => { loadData(); }, []);

  const handleVerify = async () => {
    setResult(null);
    setVerifying(true);

    try {
      let res;
      if (activeTab === 'credly') {
        if (!badgeUrl.trim()) {
          setResult({ ok: false, error: '// badge url required.' });
          setVerifying(false);
          return;
        }
        res = await window.OBC_API.verifyCert('credly', { badge_url: badgeUrl.trim() });
      } else if (activeTab === 'htb') {
        if (!profileUrl.trim()) {
          setResult({ ok: false, error: '// profile url required.' });
          setVerifying(false);
          return;
        }
        res = await window.OBC_API.verifyCert('htb', {
          profile_url: profileUrl.trim(),
          claimed_rank: claimedRank,
        });
      } else if (activeTab === 'manual') {
        if (!selectedCertType) {
          setResult({ ok: false, error: '// select a certification type.' });
          setVerifying(false);
          return;
        }
        if (!manualUrl.trim()) {
          setResult({ ok: false, error: '// verification url required.' });
          setVerifying(false);
          return;
        }
        res = await window.OBC_API.verifyCert('manual', {
          cert_type_id: selectedCertType,
          verification_url: manualUrl.trim(),
        });
      }

      if (res && !res.ok && res.error) {
        const errMap = {
          BADGE_NOT_FOUND: '// badge not found. check the url and try again.',
          CERT_NOT_RECOGNIZED: '// badge does not match a recognized certification.',
          CERT_ALREADY_VERIFIED: '// you have already verified this certification.',
          INVALID_BADGE_URL: '// invalid credly badge url format.',
          INVALID_PROFILE_URL: '// invalid hack the box profile url.',
          MISSING_BADGE_URL: '// badge url required.',
          MISSING_PARAMS: '// all fields are required.',
          MISSING_CERT_TYPE: '// select a certification type.',
        };
        setResult({ ok: false, error: errMap[res.error] || '// ' + res.error.toLowerCase() });
      } else if (res && res.ok) {
        setResult({
          ok: true,
          cert_name: res.cert?.name,
          level: res.cert?.level,
          points_awarded: res.cert?.points_awarded,
          status: res.status || 'VERIFIED',
          tier_changed: res.tier_changed,
          new_tier: res.new_tier,
        });
        // Refresh certs list after successful verification
        const certRes = await window.OBC_API.getMyCerts();
        if (certRes) {
          setMyCerts(certRes.certs || []);
          setTotalPoints(certRes.total_cert_points || 0);
        }
        // Clear form fields on success
        if (activeTab === 'credly') setBadgeUrl('');
        if (activeTab === 'htb') setProfileUrl('');
        if (activeTab === 'manual') { setManualUrl(''); setSelectedCertType(''); }
      }
    } catch (e) {
      setResult({ ok: false, error: '// verification failed. try again.' });
    }

    setVerifying(false);
  };

  if (loading) {
    return (
      <div>
        <h3 style={{ fontSize: 22, fontWeight: 800, color: '#FFF', letterSpacing: '0.04em', textTransform: 'uppercase', margin: '0 0 6px' }}>./certifications</h3>
        <div style={{ fontSize: 12, color: '#BFBFBF', letterSpacing: '0.18em' }}>// loading certification data...</div>
      </div>
    );
  }

  return (
    <div>
      <h3 style={{ fontSize: 22, fontWeight: 800, color: '#FFF', letterSpacing: '0.04em', textTransform: 'uppercase', margin: '0 0 6px' }}>./certifications</h3>
      <div style={{ fontSize: 12, color: '#BFBFBF', letterSpacing: '0.18em', marginBottom: 22 }}>// verify your cyber credentials. earn points toward your rank.</div>

      {/* ==================== MY CERTIFICATIONS ==================== */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 11, color: '#BFBFBF', letterSpacing: '0.22em', fontWeight: 700, marginBottom: 14 }}>// MY CERTIFICATIONS</div>

        {myCerts.length === 0 ? (
          <div style={{ padding: 22, background: '#0A0A0A', border: '1px dashed rgba(255,255,255,0.22)', fontSize: 12, color: '#9A9A9A', letterSpacing: '0.06em', lineHeight: 1.7 }}>
            // no verified certifications. link your credly or htb profile below.
          </div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
            {myCerts.map((cert) => {
              const ls = getLevelStyle(cert.level);
              return (
                <div key={cert.id} style={{
                  display: 'flex', background: '#0A0A0A',
                  border: `1px solid rgba(255,255,255,0.22)`,
                }}>
                  {/* Level accent strip */}
                  <div style={{ width: 4, background: ls.border, flexShrink: 0 }}></div>
                  <div style={{ padding: '14px 16px', flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8 }}>
                      <span style={{ fontSize: 14, fontWeight: 800, color: '#FFF', letterSpacing: '0.04em', lineHeight: 1.3 }}>{cert.cert_name}</span>
                      <span style={{
                        padding: '2px 8px', fontSize: 9, fontWeight: 700, letterSpacing: '0.18em',
                        border: `1px solid ${ls.border}`, color: ls.border, background: ls.bg,
                        whiteSpace: 'nowrap',
                      }}>{ls.label}</span>
                    </div>
                    <div style={{ marginTop: 8, fontSize: 11, color: '#9A9A9A', letterSpacing: '0.06em', lineHeight: 1.6 }}>
                      <div>{'>'} {cert.provider_name}</div>
                      <div>{'>'} +{cert.points_awarded} pts</div>
                      <div>{'>'} verified: {cert.verified_at ? cert.verified_at.slice(0, 10) : '—'}</div>
                    </div>
                    {cert.status === 'PENDING' && (
                      <div style={{ marginTop: 8, padding: '3px 8px', display: 'inline-block', border: '1px solid #FFD23F', color: '#FFD23F', fontSize: 9, letterSpacing: '0.18em', fontWeight: 700 }}>PENDING REVIEW</div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {myCerts.length > 0 && (
          <div style={{ marginTop: 12, padding: '10px 14px', background: 'rgba(0,255,65,0.04)', border: '1px solid rgba(0,255,65,0.22)', fontSize: 12, color: '#00FF41', letterSpacing: '0.08em' }}>
            $ total cert points: <span style={{ fontWeight: 800 }}>{totalPoints} pts</span>
          </div>
        )}
      </div>

      {/* ==================== VERIFY CERTIFICATION ==================== */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 11, color: '#BFBFBF', letterSpacing: '0.22em', fontWeight: 700, marginBottom: 14 }}>// VERIFY CERTIFICATION</div>

        {/* Tab bar */}
        <div style={{ display: 'flex', gap: 4, marginBottom: 18 }}>
          {TABS.map((tab) => (
            <button key={tab.id} onClick={() => { setActiveTab(tab.id); setResult(null); }} style={{
              padding: '10px 16px', background: activeTab === tab.id ? '#00FF41' : 'transparent',
              color: activeTab === tab.id ? '#000' : '#E0E0E0',
              border: `1px solid ${activeTab === tab.id ? '#00FF41' : 'rgba(255,255,255,0.22)'}`,
              fontFamily: 'inherit', fontSize: 11, fontWeight: 700, letterSpacing: '0.14em',
              cursor: 'pointer', borderRadius: 2,
            }}>{tab.label}</button>
          ))}
        </div>

        <div style={{ padding: 20, background: '#0A0A0A', border: '1px solid rgba(255,255,255,0.22)' }}>
          {/* CREDLY tab */}
          {activeTab === 'credly' && (
            <div>
              <div style={{ fontSize: 11, color: '#00E5FF', letterSpacing: '0.22em', marginBottom: 14 }}>$ ./verify --provider credly</div>
              <CertInput
                label="BADGE URL"
                value={badgeUrl}
                onChange={setBadgeUrl}
                placeholder="https://www.credly.com/badges/..."
              />
              <div style={{ marginTop: 14 }}>
                <VerifyBtn loading={verifying} onClick={handleVerify} />
              </div>
            </div>
          )}

          {/* HACK THE BOX tab */}
          {activeTab === 'htb' && (
            <div>
              <div style={{ fontSize: 11, color: '#00FF41', letterSpacing: '0.22em', marginBottom: 14 }}>$ ./verify --provider htb</div>
              <CertInput
                label="PROFILE URL"
                value={profileUrl}
                onChange={setProfileUrl}
                placeholder="https://app.hackthebox.com/profile/..."
              />
              <div style={{ marginTop: 14 }}>
                <div style={{ fontSize: 11, letterSpacing: '0.22em', color: '#E0E0E0', fontWeight: 700, marginBottom: 8 }}>{'>'} CLAIMED RANK</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {HTB_RANKS.map((rank) => (
                    <button key={rank} onClick={() => setClaimedRank(rank)} style={{
                      padding: '8px 14px', background: claimedRank === rank ? 'rgba(0,255,65,0.12)' : 'transparent',
                      border: `1px solid ${claimedRank === rank ? '#00FF41' : 'rgba(255,255,255,0.22)'}`,
                      color: claimedRank === rank ? '#00FF41' : '#BFBFBF',
                      fontFamily: 'inherit', fontSize: 11, letterSpacing: '0.1em', fontWeight: 600,
                      cursor: 'pointer', borderRadius: 2,
                    }}>{rank}</button>
                  ))}
                </div>
              </div>
              <div style={{ marginTop: 14 }}>
                <VerifyBtn loading={verifying} onClick={handleVerify} />
              </div>
            </div>
          )}

          {/* MANUAL tab */}
          {activeTab === 'manual' && (
            <div>
              <div style={{ fontSize: 11, color: '#FFD23F', letterSpacing: '0.22em', marginBottom: 14 }}>$ ./verify --provider manual</div>
              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 11, letterSpacing: '0.22em', color: '#E0E0E0', fontWeight: 700, marginBottom: 6 }}>{'>'} CERTIFICATION TYPE</div>
                <select
                  value={selectedCertType}
                  onChange={(e) => setSelectedCertType(e.target.value)}
                  style={{
                    width: '100%', background: '#000', border: '1px solid rgba(255,255,255,0.28)',
                    color: selectedCertType ? '#FFF' : '#9A9A9A', fontFamily: 'inherit', fontSize: 13,
                    padding: '10px 12px', borderRadius: 2, cursor: 'pointer',
                    appearance: 'none', WebkitAppearance: 'none',
                    backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%239A9A9A' fill='none' stroke-width='1.5'/%3E%3C/svg%3E")`,
                    backgroundRepeat: 'no-repeat',
                    backgroundPosition: 'right 12px center',
                  }}
                  onFocus={(e) => { e.target.style.borderColor = '#00FF41'; e.target.style.boxShadow = '0 0 0 1px #00FF41'; }}
                  onBlur={(e) => { e.target.style.borderColor = 'rgba(255,255,255,0.28)'; e.target.style.boxShadow = 'none'; }}
                >
                  <option value="" disabled>select certification...</option>
                  {providers.map((prov) => (
                    <optgroup key={prov.id} label={prov.name}>
                      {(prov.certs || []).map((c) => (
                        <option key={c.id} value={c.id}>{c.name} [{(getLevelStyle(c.level).label)}] — {c.points} pts</option>
                      ))}
                    </optgroup>
                  ))}
                </select>
              </div>
              <CertInput
                label="VERIFICATION URL"
                value={manualUrl}
                onChange={setManualUrl}
                placeholder="https://link-to-your-cert-or-badge..."
              />
              <div style={{ marginTop: 6, fontSize: 10, color: '#9A9A9A', letterSpacing: '0.06em' }}>// manual submissions are reviewed within 48 hours.</div>
              <div style={{ marginTop: 14 }}>
                <VerifyBtn loading={verifying} onClick={handleVerify} label="./submit" />
              </div>
            </div>
          )}

          {/* Result display */}
          {result && (
            <div style={{ marginTop: 18 }}>
              {result.ok ? (
                <div style={{ padding: '14px 16px', border: '1px solid #00FF41', background: 'rgba(0,255,65,0.06)' }}>
                  <div style={{ fontSize: 12, color: '#00FF41', letterSpacing: '0.08em', lineHeight: 1.8 }}>
                    {result.status === 'PENDING' ? (
                      <>
                        $ verification submitted<br />
                        {'>'} status: <span style={{ color: '#FFD23F', fontWeight: 700 }}>[PENDING REVIEW]</span><br />
                        {'>'} you will be notified when reviewed.
                      </>
                    ) : (
                      <>
                        $ verification complete<br />
                        {'>'} cert: <span style={{ fontWeight: 800 }}>{result.cert_name || 'VERIFIED'}</span><br />
                        {result.level && <>{'>'} level: <span style={{ color: getLevelStyle(result.level).border, fontWeight: 700 }}>[{getLevelStyle(result.level).label}]</span><br /></>}
                        {result.points_awarded != null && <>{'>'} points awarded: <span style={{ fontWeight: 800 }}>+{result.points_awarded} pts</span><br /></>}
                        {'>'} status: <span style={{ fontWeight: 700 }}>[VERIFIED]</span>
                        {result.tier_changed && <><br />{'>'} <span style={{ color: '#FFD23F', fontWeight: 800 }}>RANK UP: {result.new_tier}</span></>}
                      </>
                    )}
                  </div>
                </div>
              ) : (
                <div style={{ padding: '14px 16px', border: '1px solid #FF3344', background: 'rgba(255,51,68,0.06)', fontSize: 12, color: '#FF3344', letterSpacing: '0.06em' }}>
                  {result.error || '// unknown error.'}
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* ==================== AVAILABLE CERTIFICATIONS (collapsible) ==================== */}
      <div>
        <div
          onClick={() => setShowCatalog(!showCatalog)}
          style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '12px 14px', background: '#0A0A0A', border: '1px solid rgba(255,255,255,0.22)',
            cursor: 'pointer', transition: 'border-color 120ms',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.borderColor = '#00FF41'; }}
          onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'rgba(255,255,255,0.22)'; }}
        >
          <span style={{ fontSize: 11, color: '#BFBFBF', letterSpacing: '0.22em', fontWeight: 700 }}>// AVAILABLE CERTIFICATIONS</span>
          <span style={{ fontSize: 11, color: '#00FF41', letterSpacing: '0.18em' }}>{showCatalog ? '[ - ] collapse' : '[ + ] expand'}</span>
        </div>

        {showCatalog && (
          <div style={{ border: '1px solid rgba(255,255,255,0.22)', borderTop: 'none', padding: 18, background: '#0A0A0A' }}>
            {providers.length === 0 ? (
              <div style={{ fontSize: 12, color: '#9A9A9A', letterSpacing: '0.06em' }}>// no certification providers configured.</div>
            ) : (
              providers.map((prov) => (
                <div key={prov.id} style={{ marginBottom: 18 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 10 }}>
                    <span style={{ fontSize: 13, fontWeight: 800, color: '#FFF', letterSpacing: '0.06em' }}>{prov.name}</span>
                    {prov.is_partner && <span style={{ fontSize: 9, padding: '2px 6px', border: '1px solid #00FF41', color: '#00FF41', letterSpacing: '0.14em', fontWeight: 700 }}>PARTNER</span>}
                    {prov.website_url && (
                      <a href={prov.website_url} target="_blank" rel="noopener noreferrer" style={{ fontSize: 10, color: '#00E5FF', letterSpacing: '0.08em', textDecoration: 'none' }}>
                        [{prov.slug}]
                      </a>
                    )}
                  </div>
                  {(prov.certs || []).length === 0 ? (
                    <div style={{ fontSize: 11, color: '#9A9A9A', paddingLeft: 14 }}>// no cert types listed.</div>
                  ) : (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                      {prov.certs.map((c) => {
                        const ls = getLevelStyle(c.level);
                        return (
                          <div key={c.id} style={{
                            display: 'flex', alignItems: 'center', gap: 12,
                            padding: '8px 14px', border: '1px solid rgba(255,255,255,0.1)',
                            background: 'rgba(255,255,255,0.02)',
                          }}>
                            <span style={{ color: '#00FF41', fontSize: 11, width: 14, flexShrink: 0 }}>{'>'}</span>
                            <span style={{ flex: 1, fontSize: 12, color: '#E0E0E0', letterSpacing: '0.04em' }}>{c.name}</span>
                            <span style={{
                              padding: '2px 8px', fontSize: 9, fontWeight: 700, letterSpacing: '0.14em',
                              border: `1px solid ${ls.border}`, color: ls.border, background: ls.bg,
                              whiteSpace: 'nowrap',
                            }}>{ls.label}</span>
                            <span style={{ fontSize: 12, fontWeight: 700, color: '#00FF41', letterSpacing: '0.06em', whiteSpace: 'nowrap' }}>+{c.points} pts</span>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              ))
            )}
            <div style={{ marginTop: 10, fontSize: 10, color: '#9A9A9A', letterSpacing: '0.06em', lineHeight: 1.6 }}>
              // submit your certs above. credly + htb are auto-verified. manual certs reviewed within 48h.
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// ===================== SHARED SUBCOMPONENTS =====================

const CertInput = ({ label, value, onChange, placeholder }) => (
  <div>
    <div style={{ fontSize: 11, letterSpacing: '0.22em', color: '#E0E0E0', fontWeight: 700, marginBottom: 6 }}>{'>'} {label}</div>
    <input
      type="url"
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      maxLength={2000}
      style={{
        width: '100%', background: '#000', border: '1px solid rgba(255,255,255,0.28)',
        color: '#FFF', fontFamily: 'inherit', fontSize: 13, padding: '10px 12px', borderRadius: 2,
      }}
      onFocus={(e) => { e.target.style.borderColor = '#00FF41'; e.target.style.boxShadow = '0 0 0 1px #00FF41'; }}
      onBlur={(e) => { e.target.style.borderColor = 'rgba(255,255,255,0.28)'; e.target.style.boxShadow = 'none'; }}
    />
  </div>
);

const VerifyBtn = ({ loading, onClick, label }) => (
  <button
    onClick={onClick}
    disabled={loading}
    style={{
      background: 'transparent', border: '1px solid #00FF41', color: '#00FF41',
      padding: '10px 18px', fontFamily: 'inherit', fontSize: 12, fontWeight: 700,
      letterSpacing: '0.18em', cursor: loading ? 'wait' : 'pointer', borderRadius: 2,
      opacity: loading ? 0.6 : 1, textTransform: 'uppercase',
    }}
  >
    {loading ? '// verifying...' : (label || './verify')}
  </button>
);

window.Certs = Certs;
