// Shared components for R.I.P. — logo, nav, Bauhaus primitives, item visual.

// ── Bauhaus logo lockup — concrete, subdued ───────────────────────────────
function Logo({ size = 'sm', onClick }) {
  const isLg = size === 'lg';
  const dotSize = isLg ? 10 : 5;
  return (
    <div className="logo" onClick={onClick} style={{ fontSize: isLg ? 64 : 22, gap: isLg ? 12 : 6 }}>
      <span className="letter">R</span>
      <span className="dot" style={{ width: dotSize, height: dotSize, background: 'var(--ice)' }} />
      <span className="letter">I</span>
      <span className="dot" style={{ width: dotSize, height: dotSize, background: 'var(--ice)' }} />
      <span className="letter">P</span>
      <span className="dot" style={{ width: dotSize, height: dotSize, background: 'var(--ice)' }} />
    </div>
  );
}

// ── User avatar dropdown ──────────────────────────────────────────────────
function UserMenu({ user, go, onSignOut, lang = 'en' }) {
  const tn = window.T[lang].nav;
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const initials = (user.displayName || user.email || '?').slice(0, 2).toUpperCase();

  React.useEffect(() => {
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        background: 'transparent', border: 'none', cursor: 'pointer', padding: 0,
      }}>
        {user.photoURL ? (
          <img src={user.photoURL} alt="" style={{ width: 32, height: 32, borderRadius: '50%', objectFit: 'cover', border: '1px solid var(--hairline)' }} />
        ) : (
          <span style={{
            width: 32, height: 32, borderRadius: '50%', background: 'var(--ink)',
            color: 'var(--paper)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'Archivo, sans-serif', fontSize: 11, fontWeight: 600, letterSpacing: '0.04em',
          }}>{initials}</span>
        )}
        <span className="mono tiny upper" style={{ color: 'var(--ink-2)', letterSpacing: '0.14em', fontSize: 10, maxWidth: 100, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {user.displayName || user.email}
        </span>
        <span style={{ fontSize: 9, color: 'var(--muted)', marginLeft: -4 }}>{open ? '▲' : '▼'}</span>
      </button>

      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 10px)', right: 0,
          background: 'var(--paper)', border: '1px solid var(--ink)',
          minWidth: 200, zIndex: 100, boxShadow: '0 8px 32px rgba(0,0,0,0.12)',
        }}>
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--hairline)' }}>
            <div className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.24em', marginBottom: 2 }}>{tn.signedInAs}</div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.email}</div>
          </div>
          {[
            { label: tn.myRIPs,          icon: '◈', action: () => { go('archive'); setOpen(false); } },
            { label: tn.profile,         icon: '◯', action: () => { go('settings'); setOpen(false); } },
            { label: tn.accountSettings, icon: '◻', action: () => { go('settings'); setOpen(false); } },
          ].map(item => (
            <button key={item.label} onClick={item.action} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              width: '100%', padding: '12px 18px', background: 'transparent', border: 'none',
              cursor: 'pointer', textAlign: 'left', borderBottom: '1px solid var(--hairline)',
              fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
              textTransform: 'uppercase', letterSpacing: '0.22em', color: 'var(--ink-2)',
              transition: 'background 0.15s',
            }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--paper-2)'}
            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
            >
              <span style={{ color: 'var(--ice)', fontSize: 12 }}>{item.icon}</span>
              {item.label}
            </button>
          ))}
          <button onClick={() => { onSignOut(); setOpen(false); }} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            width: '100%', padding: '12px 18px', background: 'transparent', border: 'none',
            cursor: 'pointer', textAlign: 'left',
            fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
            textTransform: 'uppercase', letterSpacing: '0.22em', color: 'var(--ink-2)',
            transition: 'background 0.15s',
          }}
          onMouseEnter={e => e.currentTarget.style.background = 'var(--paper-2)'}
          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
          >
            <span style={{ color: 'var(--steel)', fontSize: 12 }}>→</span>
            {tn.signOut}
          </button>
        </div>
      )}
    </div>
  );
}

// ── Navigation bar ────────────────────────────────────────────────────────
function Nav({ screen, go, user, onSignOut, lang = 'en', toggleLang }) {
  const tn = window.T[lang].nav;
  return (
    <nav className="nav">
      <div className="page nav-inner">
        <div className="flex gap-3" style={{ alignItems: 'baseline' }}>
          <Logo onClick={() => go('landing')} />
          <span className="logo-sub mono">REST IN POSSESSIONS</span>
        </div>
        <div className="nav-links">
          <a className={'link ' + (screen === 'landing' ? 'active' : '')} onClick={() => go('landing')}>{tn.about}</a>
          <a className={'link ' + (['archive','item','add-item','bequest'].includes(screen) ? 'active' : '')} onClick={() => go('archive')}>{tn.myArchive}</a>
          <a className="link" onClick={() => {
            if (screen === 'landing') {
              document.getElementById('how-it-works')?.scrollIntoView({ behavior: 'smooth' });
            } else {
              go('landing');
              setTimeout(() => document.getElementById('how-it-works')?.scrollIntoView({ behavior: 'smooth' }), 80);
            }
          }}>{tn.howItWorks}</a>
          <a className={'link ' + (screen === 'marketplace' ? 'active' : '')} onClick={() => go('marketplace')}>{tn.marketplace}</a>
          <a className={'link ' + (screen === 'notary' ? 'active' : '')} onClick={() => go('notary')}>{tn.notary}</a>
          <span style={{ width: 1, height: 22, background: 'var(--hairline)' }} />
          <button onClick={toggleLang} style={{
            background: 'transparent', border: '1px solid var(--hairline)',
            padding: '5px 10px', cursor: 'pointer', borderRadius: 2,
            fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
            letterSpacing: '0.14em', display: 'inline-flex', gap: 5, alignItems: 'center',
          }}>
            <span style={{ color: lang === 'en' ? 'var(--ink)' : 'var(--muted)', fontWeight: lang === 'en' ? 600 : 400 }}>EN</span>
            <span style={{ color: 'var(--hairline)' }}>·</span>
            <span style={{ color: lang === 'zh' ? 'var(--ink)' : 'var(--muted)', fontWeight: lang === 'zh' ? 600 : 400 }}>中</span>
          </button>
          {user ? (
            <UserMenu user={user} go={go} onSignOut={onSignOut} lang={lang} />
          ) : (
            <button className="btn ghost" style={{ padding: '10px 16px' }} onClick={() => go('signin')}>{tn.signIn}</button>
          )}
          <button className="btn" onClick={() => go('add-item')}>{tn.beginAWill}</button>
        </div>
      </div>
    </nav>
  );
}

// ── Bauhaus shape glyph (circle / square / triangle) ──────────────────────
function Glyph({ kind, size = 24, color = 'currentColor', style = {} }) {
  const common = { width: size, height: size, display: 'inline-block', ...style };
  if (kind === 'circle')  return <span style={{ ...common, background: color, borderRadius: '50%' }} />;
  if (kind === 'square')  return <span style={{ ...common, background: color }} />;
  if (kind === 'triangle') {
    return (
      <span style={{
        ...common, background: 'transparent',
        width: 0, height: 0,
        borderLeft: `${size/2}px solid transparent`,
        borderRight: `${size/2}px solid transparent`,
        borderBottom: `${size * 0.86}px solid ${color}`,
      }} />
    );
  }
  return null;
}

// ── Item visual — line-drawing placeholder per item ───────────────────────
// Wireframe Bauhaus compositions: thin outlines on a flat concrete plane.
// The whole archive should read like blueprint paper, not posters.
function ItemVisual({ item, w = '100%', h = 320, frameless = false }) {
  const h32 = [...item.id].reduce((a, c) => (a * 31 + c.charCodeAt(0)) | 0, 0);
  const r = (n) => ((h32 >> n) & 0xff) / 255;
  const [base, stroke] = item.swatch;
  const layout = Math.floor(r(2) * 4);
  const off = 18 + r(6) * 30;
  return (
    <div style={{
      position: 'relative',
      width: w, height: h,
      background: base,
      overflow: 'hidden',
      boxShadow: frameless ? 'none' : 'inset 0 0 0 1px rgba(0,0,0,0.10)',
    }}>
      {/* light gradient — concrete wall lit from upper-left */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(135deg, rgba(255,255,255,0.10), transparent 40%, rgba(0,0,0,0.10))',
        pointerEvents: 'none',
      }} />
      <svg viewBox="0 0 200 200" preserveAspectRatio="xMidYMid meet"
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        <g fill="none" stroke={stroke} strokeWidth="0.8">
          {layout === 0 && (
            <>
              <circle cx="100" cy="108" r="58" />
              <rect x="30" y="38" width="32" height="32" />
            </>
          )}
          {layout === 1 && (
            <>
              <rect x="40" y="40" width="120" height="120" />
              <circle cx="155" cy="55" r="16" />
            </>
          )}
          {layout === 2 && (
            <>
              <polygon points="100,38 168,160 32,160" />
              <circle cx={70 + off} cy="70" r="10" />
            </>
          )}
          {layout === 3 && (
            <>
              <line x1="0" y1="130" x2="200" y2="130" />
              <circle cx="100" cy="100" r="42" />
              <rect x="24" y="24" width="12" height="12" />
            </>
          )}
          {/* faint axis lines */}
          <line x1="100" y1="0" x2="100" y2="200" opacity="0.10" strokeDasharray="1 4" />
          <line x1="0" y1="100" x2="200" y2="100" opacity="0.10" strokeDasharray="1 4" />
        </g>
        {/* register marks */}
        <g stroke={stroke} strokeWidth="0.5" opacity="0.5">
          <line x1="6" y1="6" x2="14" y2="6" />
          <line x1="6" y1="6" x2="6" y2="14" />
          <line x1="194" y1="194" x2="186" y2="194" />
          <line x1="194" y1="194" x2="194" y2="186" />
        </g>
      </svg>
      {/* spec labels — exhibition wall didactic style */}
      <div className="mono" style={{
        position: 'absolute', left: 12, bottom: 10,
        fontSize: 9, letterSpacing: '0.18em', textTransform: 'uppercase',
        color: stroke,
      }}>
        {item.category} · {item.year}
      </div>
      <div className="mono" style={{
        position: 'absolute', right: 12, top: 10,
        fontSize: 9, letterSpacing: '0.18em', textTransform: 'uppercase',
        color: stroke, opacity: 0.7,
      }}>
        № {item.id.slice(0, 6).toUpperCase()}
      </div>
    </div>
  );
}

// ── Form field — bare-line input ─────────────────────────────────────────
function FormField({ label, hint, value, onChange, large, multiline, rows = 4, type = 'text', options = [] }) {
  const [focus, setFocus] = React.useState(false);
  const filled = Boolean(value);
  const borderColor = focus ? 'var(--ice)' : filled ? 'var(--ink)' : 'var(--rule)';
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10, flexWrap: 'wrap', gap: 6 }}>
        <span className="mono tiny upper" style={{ color: focus ? 'var(--ice)' : 'var(--muted)', letterSpacing: '0.28em', transition: 'color 0.2s' }}>
          {label}
        </span>
        {hint && <span className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.18em', opacity: 0.7, fontSize: 9 }}>{hint}</span>}
      </div>
      <div style={{ borderBottom: `1px solid ${borderColor}`, padding: '8px 0 12px', transition: 'border-color 0.2s' }}>
        {type === 'select' ? (
          <select value={value} onChange={e => onChange(e.target.value)}
            onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
            style={{ border: 'none', outline: 'none', background: 'transparent', width: '100%',
              fontFamily: 'Archivo, sans-serif', fontSize: large ? 22 : 16,
              appearance: 'none', cursor: 'pointer', color: 'var(--ink)' }}>
            {options.map(o => <option key={o} value={o}>{o}</option>)}
          </select>
        ) : multiline ? (
          <textarea value={value} onChange={e => onChange(e.target.value)}
            onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
            rows={rows}
            style={{ border: 'none', outline: 'none', background: 'transparent', resize: 'vertical', width: '100%',
              fontFamily: 'Fraunces, serif', fontSize: 16, lineHeight: 1.65, fontWeight: 300,
              fontStyle: 'italic', color: 'var(--ink-2)' }} />
        ) : (
          <input type={type} value={value} onChange={e => onChange(e.target.value)}
            onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
            style={{ border: 'none', outline: 'none', background: 'transparent', width: '100%',
              fontFamily: 'Archivo, sans-serif', fontSize: large ? 22 : 16, color: 'var(--ink)' }} />
        )}
      </div>
    </div>
  );
}

// ── Bar submit — fills on hover/action ───────────────────────────────────
function BarSubmit({ label = 'Submit', done = 'Done', onClick }) {
  const [hover, setHover] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const handle = () => {
    if (busy) return;
    setBusy(true);
    setTimeout(() => setBusy(false), 1800);
    onClick?.();
  };
  return (
    <button
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      onClick={handle}
      style={{
        position: 'relative', display: 'inline-flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 16, background: 'var(--ink)', color: 'var(--paper)',
        border: '1px solid var(--ink)', cursor: 'pointer',
        padding: '16px 24px', overflow: 'hidden', minWidth: 200,
        fontFamily: 'Archivo, sans-serif', fontSize: 11,
        letterSpacing: '0.32em', textTransform: 'uppercase', fontWeight: 500,
      }}>
      <span style={{
        position: 'absolute', top: 0, bottom: 0, left: 0,
        right: (hover || busy) ? 0 : '100%',
        background: 'linear-gradient(90deg, #1f2a36, #3D4550)',
        transition: 'right 0.4s cubic-bezier(0.7, 0, 0.3, 1)',
      }} />
      <span style={{ position: 'relative', zIndex: 1 }}>{busy ? done : label}</span>
      <span style={{ position: 'relative', zIndex: 1, fontSize: 16 }}>→</span>
    </button>
  );
}

// ── Footer ────────────────────────────────────────────────────────────────
function Footer({ lang = 'en' }) {
  const tf = window.T[lang].footer;
  return (
    <footer style={{ background: 'var(--ink)', color: 'var(--paper)', marginTop: 120, padding: '64px 0 32px' }}>
      <div className="page">
        <div className="grid" style={{ gridTemplateColumns: '1.4fr 1fr 1fr 1fr', gap: 48, alignItems: 'flex-start' }}>
          <div>
            <div className="display" style={{ fontSize: 48, lineHeight: 0.9 }}>
              R<span style={{ color: 'var(--ice)' }}>.</span>I<span style={{ color: 'var(--ice)' }}>.</span>P<span style={{ color: 'var(--ice)' }}>.</span>
            </div>
            <div className="mono tiny upper" style={{ marginTop: 16, color: 'rgba(239,239,237,0.55)', letterSpacing: '0.22em' }}>
              {tf.est}
            </div>
            <p className="serif" style={{ fontSize: 16, lineHeight: 1.55, color: 'rgba(239,239,237,0.65)', maxWidth: 320, marginTop: 24 }}>
              {tf.tagline}
            </p>
          </div>
          {[
            [tf.platform, tf.platformLinks],
            [tf.estate,   tf.estateLinks],
            [tf.house,    tf.houseLinks],
          ].map(([title, links]) => (
            <div key={title}>
              <div className="mono tiny upper" style={{ color: 'var(--ice)', marginBottom: 22, letterSpacing: '0.22em' }}>{title}</div>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
                {links.map(l => <li key={l} style={{ fontSize: 14, color: 'rgba(239,239,237,0.78)' }}>{l}</li>)}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ height: 1, background: 'rgba(239,239,237,0.14)', margin: '64px 0 24px' }} />
        <div className="flex" style={{ justifyContent: 'space-between' }}>
          <span className="mono tiny upper" style={{ color: 'rgba(239,239,237,0.42)', letterSpacing: '0.22em' }}>{tf.copyright}</span>
          <span className="mono tiny upper" style={{ color: 'rgba(239,239,237,0.42)', letterSpacing: '0.22em' }}>{tf.motto}</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Logo, Nav, Glyph, ItemVisual, Footer, FormField, BarSubmit, UserMenu });
