/* ============================================================
   TechManager — PROFILE (credentials, LinkedIn share, attempts)
   ============================================================ */

/* ---- Shareable credential ---- */
const Credential = ({ cert, user, attempt }) => (
  <div style={{ position: 'relative', borderRadius: 16, overflow: 'hidden', border: '1px solid var(--border-strong)',
    background: `radial-gradient(600px 300px at 100% 0%, ${cert.color}33, transparent), linear-gradient(160deg, var(--panel-2), var(--bg-soft))` }}>
    <div style={{ padding: 28 }}>
      <div className="between">
        <div className="brand" style={{ fontSize: 16 }}><span className="brand-dot" /> <span>Tech<span style={{ color: 'var(--blue-2)' }}>Manager</span></span></div>
        <span className="badge badge-pass"><Icon name="award" size={12} /> Verified credential</span>
      </div>
      <div className="flex gap-16" style={{ alignItems: 'center', marginTop: 26 }}>
        <Orb cert={cert} size={72} />
        <div>
          <div className="dim" style={{ fontSize: 12, letterSpacing: '.1em', textTransform: 'uppercase', fontWeight: 700 }}>This certifies that</div>
          <div className="display" style={{ fontSize: 24 }}>{user.name}</div>
        </div>
      </div>
      <div style={{ marginTop: 22 }}>
        <div className="dim" style={{ fontSize: 12, letterSpacing: '.1em', textTransform: 'uppercase', fontWeight: 700 }}>has earned</div>
        <div className="display text-grad" style={{ fontSize: 30, marginTop: 4 }}>{cert.name}</div>
      </div>
      <div className="between" style={{ marginTop: 26, paddingTop: 18, borderTop: '1px solid var(--border)', flexWrap: 'wrap', gap: 12 }}>
        <div><div className="dim" style={{ fontSize: 11.5 }}>SCORE</div><div style={{ fontWeight: 800 }}>{attempt ? attempt.score + '%' : '—'}</div></div>
        <div><div className="dim" style={{ fontSize: 11.5 }}>ISSUED</div><div style={{ fontWeight: 800 }}>{attempt ? new Date(attempt.date).toLocaleDateString() : '—'}</div></div>
        <div><div className="dim" style={{ fontSize: 11.5 }}>VALIDITY</div><div style={{ fontWeight: 800 }}>Lifetime</div></div>
        <div><div className="dim" style={{ fontSize: 11.5 }}>CREDENTIAL ID</div><div style={{ fontWeight: 800, fontFamily: 'monospace', fontSize: 13 }}>TM-{cert.id.slice(-4).toUpperCase()}-{(attempt ? attempt.id : 'XXXX').slice(-4).toUpperCase()}</div></div>
      </div>
    </div>
  </div>
);

const linkedInAddUrl = (cert) => {
  const p = new URLSearchParams({
    startTask: 'CERTIFICATION_NAME',
    name: cert.name,
    organizationName: 'TechManager',
    certUrl: 'https://techmanager.example/verify',
  });
  return 'https://www.linkedin.com/profile/add?' + p.toString();
};
const linkedInShareUrl = (cert) => {
  const text = `I just earned the ${cert.name} credential on TechManager — building technical credibility as a leader. `;
  return 'https://www.linkedin.com/sharing/share-offsite/?url=' + encodeURIComponent('https://techmanager.example/c/' + cert.slug) + '&summary=' + encodeURIComponent(text);
};

/* ---- Attempt row with expandable area breakdown ---- */
const AttemptRow = ({ a }) => {
  const [open, setOpen] = useState(false);
  return (
    <div className="card">
      <button onClick={() => setOpen((o) => !o)} className="between" style={{ width: '100%', padding: '16px 20px', background: 'none', border: 'none', textAlign: 'left' }}>
        <div className="center gap-16">
          <span className={'badge ' + (a.passed ? 'badge-pass' : 'badge-fail')}>{a.passed ? 'Passed' : 'Not passed'}</span>
          <div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>{a.certName}</div>
            <div className="dim" style={{ fontSize: 12.5 }}>{new Date(a.date).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' })} · {a.correctCount}/{a.total} correct</div>
          </div>
        </div>
        <div className="center gap-16">
          <span className="display" style={{ fontSize: 24, color: a.passed ? 'var(--green)' : 'var(--red)' }}>{a.score}%</span>
          <Icon name={open ? 'up' : 'down'} size={18} style={{ color: 'var(--dim)' }} />
        </div>
      </button>
      {open && (
        <div style={{ padding: '4px 20px 20px' }}>
          <div className="dim" style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.05em', textTransform: 'uppercase', marginBottom: 12 }}>Areas to study — by domain</div>
          <div className="grid gap-12">
            {a.areaBreakdown.map((ar) => (
              <div key={ar.area}>
                <div className="between" style={{ marginBottom: 6 }}>
                  <span style={{ fontSize: 13.5 }} className="center gap-8">{ar.weak ? <Icon name="target" size={13} style={{ color: 'var(--amber)' }} /> : <Icon name="checkCircle" size={13} style={{ color: 'var(--green)' }} />}{ar.area}</span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: ar.weak ? 'var(--amber)' : 'var(--green)' }}>{ar.pct}%</span>
                </div>
                <div className="bar-track" style={{ height: 6 }}><div className="bar-fill" style={{ width: ar.pct + '%', background: ar.weak ? 'linear-gradient(90deg,#d39a14,var(--amber))' : 'linear-gradient(90deg,#0e9488,var(--green))' }} /></div>
              </div>
            ))}
          </div>
          <p className="dim" style={{ fontSize: 12, marginTop: 14, marginBottom: 0 }}>For exam integrity, individual questions and your specific answers are never revealed.</p>
        </div>
      )}
    </div>
  );
};

/* ---- Profile page ---- */
const Profile = ({ db, go }) => {
  const [shareCert, setShareCert] = useState(null);
  const earnedCerts = db.user.certificates.map((id) => TM.certById(id)).filter(Boolean);
  const attempts = db.user.attempts;
  const bestFor = (certId) => attempts.filter((a) => a.certId === certId && a.passed).sort((x, y) => y.score - x.score)[0];
  const passedCount = attempts.filter((a) => a.passed).length;

  return (
    <div className="fadein wrap section tight">
      {/* header */}
      <div className="card" style={{ padding: 28, position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(500px 220px at 90% -40%, rgba(47,125,246,0.2), transparent)', pointerEvents: 'none' }} />
        <div className="between" style={{ flexWrap: 'wrap', gap: 20, position: 'relative' }}>
          <div className="center gap-16">
            <div style={{ width: 72, height: 72, borderRadius: '50%', background: 'linear-gradient(135deg, var(--blue-2), var(--blue-deep))', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 28, fontFamily: 'var(--display)' }}>{db.user.name.split(' ').map((s) => s[0]).join('')}</div>
            <div>
              <h1 className="display" style={{ fontSize: 30 }}>{db.user.name}</h1>
              <p className="muted" style={{ margin: '4px 0 0' }}>{db.user.title} · {db.user.email}</p>
            </div>
          </div>
          <div className="flex gap-24">
            <div style={{ textAlign: 'center' }}><div className="display" style={{ fontSize: 30 }}>{earnedCerts.length}</div><div className="dim" style={{ fontSize: 12, textTransform: 'uppercase', letterSpacing: '.06em' }}>Credentials</div></div>
            <div style={{ textAlign: 'center' }}><div className="display" style={{ fontSize: 30 }}>{attempts.length}</div><div className="dim" style={{ fontSize: 12, textTransform: 'uppercase', letterSpacing: '.06em' }}>Attempts</div></div>
            <div style={{ textAlign: 'center' }}><div className="display" style={{ fontSize: 30 }}>{passedCount}</div><div className="dim" style={{ fontSize: 12, textTransform: 'uppercase', letterSpacing: '.06em' }}>Passed</div></div>
          </div>
        </div>
      </div>

      {/* credentials */}
      <h2 className="display" style={{ fontSize: 24, marginTop: 40, marginBottom: 4 }}>My credentials</h2>
      <p className="muted" style={{ marginTop: 0 }}>Lifetime credentials you've earned. Share them straight to LinkedIn.</p>
      {earnedCerts.length === 0 ? (
        <div className="card" style={{ padding: 40, textAlign: 'center', marginTop: 16 }}>
          <Icon name="award" size={34} style={{ color: 'var(--dim)' }} />
          <p className="muted" style={{ marginTop: 12 }}>No credentials yet. Pass an exam to earn your first lifetime credential.</p>
          <button className="btn btn-primary" style={{ marginTop: 6 }} onClick={() => go('certs')}>Browse certifications <Icon name="arrow" size={15} /></button>
        </div>
      ) : (
        <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(360px, 1fr))', gap: 20, marginTop: 16 }}>
          {earnedCerts.map((c) => (
            <div key={c.id}>
              <Credential cert={c} user={db.user} attempt={bestFor(c.id)} />
              <div className="flex gap-12" style={{ marginTop: 12 }}>
                <button className="btn btn-primary" style={{ flex: 1, background: 'linear-gradient(180deg,#2f88e0,#0a66c2)' }} onClick={() => window.open(linkedInAddUrl(c), '_blank')}>
                  <Icon name="linkedin" size={17} /> Add to LinkedIn
                </button>
                <button className="btn btn-ghost" onClick={() => setShareCert(c)}><Icon name="share" size={16} /> Share</button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* attempts */}
      <h2 className="display" style={{ fontSize: 24, marginTop: 48, marginBottom: 4 }}>Exam attempts</h2>
      <p className="muted" style={{ marginTop: 0 }}>Every attempt, with score, pass status, and the domains to focus on. Expand any attempt for its study breakdown.</p>
      {attempts.length === 0 ? (
        <div className="card" style={{ padding: 32, textAlign: 'center', marginTop: 16 }} ><span className="muted">No attempts yet.</span></div>
      ) : (
        <div className="grid gap-12" style={{ marginTop: 16 }}>
          {attempts.map((a) => <AttemptRow key={a.id} a={a} />)}
        </div>
      )}

      {/* share modal */}
      <Modal open={!!shareCert} onClose={() => setShareCert(null)} width={460}>
        {shareCert && (
          <div style={{ padding: 26 }}>
            <div className="between" style={{ marginBottom: 16 }}><h3 className="display" style={{ fontSize: 21 }}>Share your credential</h3><button className="btn btn-soft btn-sm" onClick={() => setShareCert(null)}><Icon name="x" size={15} /></button></div>
            <Credential cert={shareCert} user={db.user} attempt={bestFor(shareCert.id)} />
            <div className="grid gap-12" style={{ marginTop: 18 }}>
              <button className="btn btn-primary btn-block" style={{ background: 'linear-gradient(180deg,#2f88e0,#0a66c2)' }} onClick={() => window.open(linkedInAddUrl(shareCert), '_blank')}><Icon name="linkedin" size={18} /> Add to LinkedIn profile</button>
              <button className="btn btn-ghost btn-block" onClick={() => window.open(linkedInShareUrl(shareCert), '_blank')}><Icon name="share" size={16} /> Share as a post</button>
              <button className="btn btn-soft btn-block" onClick={() => { navigator.clipboard && navigator.clipboard.writeText('https://techmanager.example/c/' + shareCert.slug); }}>Copy verification link</button>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

Object.assign(window, { Credential, AttemptRow, Profile, linkedInAddUrl, linkedInShareUrl });
