// Header.jsx — top bar with logo, kid name, progress
// BadgeRail.jsx — badge row under progress

function Header({ kidName, onEditName, total, seen, theme, onToggleTheme, auth, onSignIn, onSignOut }) {
  const pct = total > 0 ? Math.round((seen / total) * 100) : 0;
  const [showSignInInfo, setShowSignInInfo] = React.useState(false);
  const infoRef = React.useRef(null);

  // Close popover on outside click / Escape
  React.useEffect(() => {
    if (!showSignInInfo) return;
    const onDown = (e) => {
      if (infoRef.current && !infoRef.current.contains(e.target)) setShowSignInInfo(false);
    };
    const onKey = (e) => { if (e.key === 'Escape') setShowSignInInfo(false); };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [showSignInInfo]);
  return (
    <header className="header">
      <div className="header__brand">
        <div className="logo">
          <svg width="28" height="28" viewBox="0 0 28 28">
            <circle cx="14" cy="14" r="12" fill="none" stroke="var(--amber)" strokeWidth="1" opacity="0.3" />
            <circle cx="14" cy="14" r="2" fill="var(--amber)" />
            <circle cx="22" cy="8" r="1.2" fill="var(--ink-100)" />
            <circle cx="6" cy="10" r="0.9" fill="var(--ink-100)" opacity="0.8" />
            <circle cx="20" cy="21" r="1" fill="var(--ink-100)" opacity="0.9" />
            <circle cx="8" cy="20" r="0.7" fill="var(--ink-100)" opacity="0.7" />
          </svg>
        </div>
        <div>
          <div className="header__title">Stars we have seen</div>
          <div className="header__sub mono">
            <span
              contentEditable
              suppressContentEditableWarning
              onBlur={e => onEditName(e.currentTarget.textContent.trim() || 'Observer')}
              className="header__name"
            >{kidName}</span>
            <span>&nbsp;· FIELD LOG</span>
          </div>
        </div>
      </div>

      <div className="header__progress">
        <div className="progress-count">
          <span className="progress-count__seen">{seen}</span>
          <span className="progress-count__of">/{total}</span>
        </div>
        <div className="progress-bar" aria-label={`${pct}% seen`}>
          <div className="progress-bar__fill" style={{ width: `${pct}%` }} />
        </div>
        <div className="progress-label mono">{pct}% OF THE CATALOG SEEN</div>
      </div>

      <div className="header__auth">
        {auth?.signedIn ? (
          <button className="authpill" onClick={onSignOut} title={`Signed in as ${auth.profile?.email || ''} — click to sign out`}>
            {auth.profile?.picture ? (
              <img src={auth.profile.picture} alt="" className="authpill__pic" referrerPolicy="no-referrer" />
            ) : (
              <span className="authpill__pic authpill__pic--initial">{(auth.profile?.name || '?')[0]}</span>
            )}
            <span className="authpill__name">{auth.profile?.given_name || auth.profile?.name || 'Signed in'}</span>
            <span className="authpill__sync mono" aria-label="Synced">
              <svg width="10" height="10" viewBox="0 0 10 10" aria-hidden="true"><path d="M2 5l2 2 4-4" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
              SYNCED
            </span>
          </button>
        ) : (
          <div className="signin" ref={infoRef}>
            <div className="signin__btn">
              <button
                type="button"
                className="signin__main"
                onClick={onSignIn}
                title="Sign in to sync your field log"
              >
                <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true" className="signin__icon">
                  <circle cx="7" cy="7" r="6" fill="none" stroke="currentColor" strokeWidth="1" opacity="0.35" />
                  <circle cx="7" cy="7" r="1.6" fill="currentColor" />
                  <circle cx="11.2" cy="3.2" r="0.7" fill="currentColor" opacity="0.8" />
                  <circle cx="3" cy="4.4" r="0.5" fill="currentColor" opacity="0.6" />
                  <circle cx="10.4" cy="10.6" r="0.6" fill="currentColor" opacity="0.7" />
                </svg>
                <span>Sign in</span>
              </button>
              <span className="signin__sep" aria-hidden="true" />
              <button
                type="button"
                className="signin__info"
                aria-label="Why sign in?"
                onClick={() => setShowSignInInfo(v => !v)}
              >
                <svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true">
                  <circle cx="6" cy="6" r="5" fill="none" stroke="currentColor" strokeWidth="1" />
                  <circle cx="6" cy="3.4" r="0.7" fill="currentColor" />
                  <rect x="5.4" y="5" width="1.2" height="4" rx="0.6" fill="currentColor" />
                </svg>
              </button>
            </div>
            {showSignInInfo && (
              <div className="signin-pop" role="dialog" aria-label="About signing in">
                <div className="signin-pop__arrow" aria-hidden="true" />
                <div className="signin-pop__kicker mono">WHY SIGN IN?</div>
                <div className="signin-pop__title">Save your progress across sessions</div>
                <p className="signin-pop__body">
                  Signing in syncs your field log — every observation, note and earned badge —
                  to your account, so you can pick up on another device or come back after
                  clearing your browser without losing a single star.
                </p>
                <ul className="signin-pop__list">
                  <li><span className="signin-pop__bullet" />Your log is stored privately to your account.</li>
                  <li><span className="signin-pop__bullet" />Works across phone, tablet and desktop.</li>
                  <li><span className="signin-pop__bullet" />Skip it and everything stays local to this browser.</li>
                </ul>
                <div className="signin-pop__actions">
                  <button className="signin-pop__primary" onClick={() => { setShowSignInInfo(false); onSignIn(); }}>
                    Sign in &amp; sync
                  </button>
                  <button className="signin-pop__ghost" onClick={() => setShowSignInInfo(false)}>
                    Not now
                  </button>
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      <button className="iconbtn" onClick={onToggleTheme} title="Toggle theme">
        {theme === 'dark' ? (
          <svg width="18" height="18" viewBox="0 0 18 18"><circle cx="9" cy="9" r="4" fill="none" stroke="currentColor" strokeWidth="1.4"/><g stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"><line x1="9" y1="1" x2="9" y2="3"/><line x1="9" y1="15" x2="9" y2="17"/><line x1="1" y1="9" x2="3" y2="9"/><line x1="15" y1="9" x2="17" y2="9"/><line x1="3.3" y1="3.3" x2="4.7" y2="4.7"/><line x1="13.3" y1="13.3" x2="14.7" y2="14.7"/><line x1="3.3" y1="14.7" x2="4.7" y2="13.3"/><line x1="13.3" y1="4.7" x2="14.7" y2="3.3"/></g></svg>
        ) : (
          <svg width="18" height="18" viewBox="0 0 18 18"><path d="M14 11A6 6 0 0 1 7 4c0-.7.1-1.3.3-1.9A6 6 0 1 0 15.9 10.7c-.6.2-1.2.3-1.9.3Z" fill="currentColor"/></svg>
        )}
      </button>
    </header>
  );
}

function BadgeRail({ badges, onOpen }) {
  return (
    <div className="badge-rail">
      {badges.map(b => {
        const clickable = b.earned;
        return (
          <button
            key={b.id}
            className="badge"
            data-earned={b.earned}
            onClick={clickable ? () => onOpen(b) : undefined}
            disabled={!clickable}
            aria-label={clickable ? `Open certificate for ${b.name}` : `${b.name}: ${b.desc}`}
          >
            <div className="medal" aria-hidden="true">
              <svg width="34" height="34" viewBox="0 0 34 34">
                {b.icon}
              </svg>
            </div>
            <div className="badge__ribbon">{b.name}</div>
            <div className="badge__desc">{b.desc}</div>
            {clickable && (
              <div className="badge__chev" aria-hidden="true">
                <svg width="10" height="10" viewBox="0 0 10 10"><path d="M3 1l4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </div>
            )}
          </button>
        );
      })}
    </div>
  );
}

Object.assign(window, { Header, BadgeRail });
