/* cst-ui.jsx — shared UI atoms for the CS Tech platform (Console aesthetic).
   Exported to window. Loads after cst-core.jsx. */

const { useState: _uS, useEffect: _uE, useRef: _uR } = React;
const _C = window.CST;
const { FONT, INK, TEXT, HAZE, HAZE_DIM, HAIR, GLASS, GLASS_HI, AMBER } = _C;

// small caps mono eyebrow
function Eyebrow({ children, color, style }) {
  return (
    <div style={{
      fontFamily: FONT, fontSize: 11, letterSpacing: 2.2, textTransform: 'uppercase',
      color: color || HAZE_DIM, fontWeight: 600, ...style,
    }}>{children}</div>);
}

// filled brand button
function PrimaryBtn({ children, onClick, accent = AMBER, disabled, style }) {
  const [hover, setHover] = _uS(false);
  return (
    <button onClick={onClick} disabled={disabled}
      onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)}
      style={{
        width: '100%', border: 'none', borderRadius: 13, cursor: disabled ? 'default' : 'pointer',
        padding: '15px 18px', fontFamily: FONT, fontSize: 15, fontWeight: 700,
        color: disabled ? 'rgba(236,237,241,0.35)' : INK,
        background: disabled ? 'rgba(236,237,241,0.07)' : accent,
        boxShadow: disabled ? 'none' : `0 0 0 1px ${accent}, 0 10px 30px -10px ${accent}, 0 0 24px -8px ${accent}`,
        transform: hover && !disabled ? 'translateY(-1px)' : 'none',
        transition: 'transform .18s ease, box-shadow .2s ease, background .2s',
        letterSpacing: 0.3, ...style,
      }}>{children}</button>);
}

// outlined secondary button
function GhostBtn({ children, onClick, style }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', borderRadius: 13, cursor: 'pointer',
      padding: '13px 18px', fontFamily: FONT, fontSize: 13.5, fontWeight: 600,
      color: HAZE, background: 'transparent', border: `1px solid ${HAIR}`, letterSpacing: 0.3, ...style,
    }}>{children}</button>);
}

// gradient scrim to seat text over the graph
function Scrim({ from = 0.0, to = 0.96 }) {
  return <div style={{
    position: 'absolute', inset: 0, pointerEvents: 'none',
    background: `linear-gradient(180deg, rgba(15,17,21,${from}) 0%, rgba(15,17,21,${from}) 34%, rgba(15,17,21,${to}) 100%)`,
  }} />;
}

// CS Tech "Console" mark — amber terminal brackets framing the CS monogram
function LogoMark({ size = 30 }) {
  return (
    <svg width={size} height={size * 0.84} viewBox="0 0 56 47" fill="none" aria-label="CS Tech Solutions">
      <path d="M23 9 H15 Q11 9 11 13 V20" stroke={AMBER} strokeWidth="3.4" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M33 38 H41 Q45 38 45 34 V27" stroke={AMBER} strokeWidth="3.4" strokeLinecap="round" strokeLinejoin="round" />
      <text x="28" y="30" textAnchor="middle" fontFamily="'Bricolage Grotesque', ui-sans-serif, system-ui, sans-serif"
        fontWeight="800" fontSize="17" letterSpacing="0.5" fill={TEXT}>CS</text>
    </svg>);
}

function LogoSlot({ sub = 'OPERATING PARTNER' }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <LogoMark size={32} />
      <div style={{ fontFamily: FONT, lineHeight: 1.05 }}>
        <div style={{ fontWeight: 700, fontSize: 13.5, letterSpacing: 0.4, color: TEXT }}>CS Tech</div>
        <div style={{ color: HAZE, fontWeight: 500, fontSize: 8.5, letterSpacing: 2.6 }}>{sub}</div>
      </div>
    </div>);
}

// top chrome: logo + optional back / refresh affordance
function TopBar({ onBack, right, dim }) {
  return (
    <div style={{
      position: 'absolute', top: 16, left: 18, right: 18, zIndex: 6,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      opacity: dim ? 0.25 : 1, transition: 'opacity .3s',
    }}>
      {onBack ? (
        <button onClick={onBack} style={{
          display: 'flex', alignItems: 'center', gap: 8, background: GLASS,
          border: `1px solid ${HAIR}`, borderRadius: 10, padding: '8px 13px 8px 10px',
          color: HAZE, fontFamily: FONT, fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
          backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)',
        }}>
          <span style={{ fontSize: 14, lineHeight: 1 }}>←</span> Tools
        </button>
      ) : <LogoSlot />}
      {right}
    </div>);
}

// progress dots
function Dots({ index, total, accent = AMBER }) {
  return (
    <div style={{ display: 'flex', gap: 6, justifyContent: 'center' }}>
      {Array.from({ length: total }).map((_, i) =>
        <div key={i} style={{
          width: i === index ? 18 : 6, height: 6, borderRadius: 3,
          background: i === index ? accent : 'rgba(236,237,241,0.22)', transition: 'width .3s, background .3s',
        }} />)}
    </div>);
}

// status chip — colored dot + label, used on scorecards
function StatusChip({ label, color, style }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 9px',
      borderRadius: 99, background: color + '1c', border: `1px solid ${color}55`,
      fontFamily: FONT, fontSize: 9.5, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase',
      color, ...style,
    }}>
      <span style={{ width: 6, height: 6, borderRadius: 99, background: color, boxShadow: `0 0 8px ${color}` }} />
      {label}
    </span>);
}

// circular score gauge
function ScoreRing({ score, accent = AMBER, size = 132, unit = '/ 100' }) {
  const s = size, c0 = s / 2, R = s * 0.394, C = 2 * Math.PI * R;
  const off = C * (1 - _C.clamp(score) / 100);
  const sw = s * 0.068;
  return (
    <div style={{ position: 'relative', width: s, height: s, flexShrink: 0 }}>
      <svg width={s} height={s} viewBox={`0 0 ${s} ${s}`} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={c0} cy={c0} r={R} fill="none" stroke="rgba(236,237,241,0.10)" strokeWidth={sw} />
        <circle cx={c0} cy={c0} r={R} fill="none" stroke={accent} strokeWidth={sw} strokeLinecap="round"
          strokeDasharray={C} strokeDashoffset={off}
          style={{ transition: 'stroke-dashoffset 1.1s cubic-bezier(.2,.8,.2,1)', filter: `drop-shadow(0 0 8px ${accent}aa)` }} />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ fontFamily: FONT, fontWeight: 800, fontSize: s * 0.3, color: TEXT, lineHeight: 1 }}>{score}</div>
        <div style={{ fontFamily: FONT, fontSize: s * 0.066, letterSpacing: 2, color: HAZE, marginTop: 3 }}>{unit}</div>
      </div>
    </div>);
}

// selectable choice card (icon dot + label + sub + arrow)
function ChoiceCard({ label, sub, accent = AMBER, onPick, glyph }) {
  const [hover, setHover] = _uS(false);
  return (
    <button onClick={onPick}
      onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)}
      style={{
        textAlign: 'left', cursor: 'pointer', borderRadius: 13, padding: '12px 14px', width: '100%',
        background: hover ? GLASS_HI : GLASS,
        border: `1px solid ${hover ? accent : HAIR}`,
        backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)',
        display: 'flex', alignItems: 'center', gap: 12, transition: 'all .18s',
      }}>
      {glyph
        ? <span style={{ width: 26, fontSize: 17, color: accent, flexShrink: 0, textAlign: 'center', fontWeight: 700 }}>{glyph}</span>
        : <span style={{ width: 9, height: 9, borderRadius: 99, background: accent, flexShrink: 0, boxShadow: `0 0 12px ${accent}` }} />}
      <span style={{ flex: 1 }}>
        <span style={{ display: 'block', fontFamily: FONT, fontWeight: 700, fontSize: 14.5, color: TEXT }}>{label}</span>
        {sub && <span style={{ display: 'block', fontFamily: FONT, fontSize: 11.5, color: HAZE, marginTop: 1, lineHeight: 1.35 }}>{sub}</span>}
      </span>
      <span style={{ color: accent, fontSize: 16 }}>→</span>
    </button>);
}

// three-dot "advisor is thinking" animation
function TypingDots({ color = AMBER }) {
  return (
    <span style={{ display: 'inline-flex', gap: 4, alignItems: 'center' }}>
      {[0, 1, 2].map((i) => (
        <span key={i} style={{
          width: 5, height: 5, borderRadius: 99, background: color,
          animation: `cstBlink 1s ${i * 0.18}s infinite ease-in-out`,
        }} />
      ))}
    </span>);
}

// scales the fixed 402×874 device to fit any viewport
function Scaler({ children }) {
  const [scale, setScale] = _uS(1);
  _uE(() => {
    const fit = () => setScale(Math.min((window.innerWidth - 24) / 402, (window.innerHeight - 24) / 874, 1.12));
    fit(); window.addEventListener('resize', fit); return () => window.removeEventListener('resize', fit);
  }, []);
  return <div style={{ transform: `scale(${scale})`, transformOrigin: 'center center', transition: 'transform .2s' }}>{children}</div>;
}

// full-bleed overlay card with directional transition; unmounts after fade
function StageCard({ active, dir, children, label }) {
  const [show, setShow] = _uS(active);
  _uE(() => {
    if (active) { setShow(true); return; }
    const id = setTimeout(() => setShow(false), 480);
    return () => clearTimeout(id);
  }, [active]);
  const offset = { left: 'translateX(-26px)', right: 'translateX(26px)', up: 'translateY(26px)' }[dir] || 'translateY(20px)';
  return (
    <div data-screen-label={label} style={{
      position: 'absolute', inset: 0, zIndex: active ? 5 : 1,
      display: show ? 'flex' : 'none', flexDirection: 'column', justifyContent: 'flex-end',
      paddingTop: 64, paddingBottom: 'calc(env(safe-area-inset-bottom, 0px) + 18px)',
      opacity: active ? 1 : 0, transform: active ? 'none' : offset,
      transition: 'opacity .45s ease, transform .45s cubic-bezier(.22,.9,.3,1)',
      pointerEvents: active ? 'auto' : 'none',
    }}>{children}</div>);
}

// share / copy action used on result cards (Web Share API + clipboard fallback)
function ShareButton({ onShare, accent, label = 'Share result' }) {
  return (
    <button onClick={onShare} style={{
      flex: 1, cursor: 'pointer', padding: '12px', borderRadius: 11, fontFamily: FONT,
      fontWeight: 700, fontSize: 12.5, color: accent, background: accent + '14',
      border: `1px solid ${accent}44`, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
    }}>
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={accent} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="18" cy="5" r="3" /><circle cx="6" cy="12" r="3" /><circle cx="18" cy="19" r="3" />
        <line x1="8.6" y1="10.7" x2="15.4" y2="6.3" /><line x1="8.6" y1="13.3" x2="15.4" y2="17.7" />
      </svg>
      {label}
    </button>);
}

// subtle brand watermark for screenshot-ready result cards
function CardWatermark({ tool }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 7, opacity: 0.7 }}>
      <LogoMark size={18} />
      <span style={{ fontFamily: FONT, fontSize: 9.5, letterSpacing: 1.5, color: HAZE_DIM }}>
        CS TECH{tool ? ' · ' + tool : ''} · cs-tech-solutions
      </span>
    </div>);
}

// a scrollable region styled with hidden scrollbars (used inside artifacts)
function ScrollArea({ children, style }) {
  return (
    <div className="cst-scroll" style={{ overflowY: 'auto', overflowX: 'hidden', ...style }}>
      {children}
    </div>);
}

// "take this idea into …" — carries the shared decision context to another tool
function HandoffRow({ currentId, onGo, accent }) {
  const others = (_C.TOOLS || []).filter((t) => t.id !== currentId);
  if (!others.length || !onGo) return null;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
      <div style={{ fontFamily: FONT, fontSize: 9, letterSpacing: 2, color: HAZE_DIM }}>TAKE THIS INTO</div>
      <div style={{ display: 'flex', gap: 8 }}>
        {others.map((t) => (
          <button key={t.id} onClick={() => onGo(t.id)} style={{
            flex: 1, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
            padding: '10px 8px', borderRadius: 11, fontFamily: FONT, fontWeight: 700, fontSize: 12,
            color: TEXT, background: GLASS, border: `1px solid ${HAIR}`,
          }}>
            <span style={{ color: accent, fontWeight: 800 }}>{t.glyph}</span>
            {t.name}
            <span style={{ color: accent }}>→</span>
          </button>
        ))}
      </div>
    </div>);
}

// ghost text "Sign in" button for unauthenticated users
function SignInBtn({ onClick }) {
  const [hover, setHover] = _uS(false);
  return (
    <button onClick={onClick}
      onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)}
      style={{
        background: 'none', border: 'none', cursor: 'pointer', padding: '6px 10px',
        fontFamily: FONT, fontSize: 12, fontWeight: 600, letterSpacing: 0.3,
        color: hover ? AMBER : HAZE, transition: 'color .15s',
      }}>Sign in</button>);
}

// avatar circle with user's first initial
function AvatarBtn({ user, subscribed }) {
  const name = (user && user.user_metadata && user.user_metadata.full_name) || '';
  const email = (user && user.email) || '';
  const initial = (name ? name.charAt(0) : email.charAt(0) || '?').toUpperCase();
  return (
    <div style={{
      width: 24, height: 24, borderRadius: 99, display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: FONT, fontSize: 11, fontWeight: 700, color: TEXT,
      background: 'rgba(236,237,241,0.12)',
      border: subscribed ? `2px solid ${AMBER}` : '2px solid transparent',
      boxShadow: subscribed ? `0 0 8px ${AMBER}44` : 'none',
    }}>{initial}</div>);
}

Object.assign(window, {
  Eyebrow, PrimaryBtn, GhostBtn, Scrim, LogoMark, LogoSlot, TopBar, Dots,
  StatusChip, ScoreRing, ChoiceCard, TypingDots, Scaler, StageCard, ScrollArea,
  ShareButton, CardWatermark, HandoffRow, SignInBtn, AvatarBtn,
});
