// Fourth Wall — shared UI primitives, logo, tokens
// All style objects are uniquely named (fwTokens) to avoid global collisions.

const fwTokens = {
  paper:   '#FDF6E3',
  paper2:  '#EEE8D5',
  paper3:  '#DDD4BE',
  ink:     '#1A1714',
  ink2:    '#3A332C',
  ink3:    '#14110E',
  mute:    '#7A7065',
  mute2:   '#9A8F82',
  rule:    '#C9BFAF',
  ruleSoft:'rgba(26,23,20,0.10)',
  oxblood: '#5C2A28',
  oxbloodDeep: '#3A1A19',
  sans:    "'Geist', -apple-system, system-ui, sans-serif",
  mono:    "'Geist Mono', ui-monospace, monospace",
  serif:   "'Instrument Serif', 'Times New Roman', serif",
};

// Proscenium mark — three sides of a rectangle, the open bottom is the fourth wall
function FWMark({ size = 32, color = fwTokens.ink, stroke = 9 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" aria-label="Fourth Wall">
      <path d="M 20 82 L 20 20 L 80 20 L 80 82"
        fill="none" stroke={color} strokeWidth={stroke}
        strokeLinecap="square" strokeLinejoin="miter" />
    </svg>
  );
}

// Micro label (mono caps with tracking)
function Micro({ children, color, style = {} }) {
  return (
    <div style={{
      fontFamily: fwTokens.mono,
      fontSize: 10.5,
      letterSpacing: '0.14em',
      textTransform: 'uppercase',
      color: color || fwTokens.mute,
      lineHeight: 1.2,
      ...style,
    }}>{children}</div>
  );
}

// Serif headline
function Serif({ children, size = 32, color, italic = false, style = {} }) {
  return (
    <div style={{
      fontFamily: fwTokens.serif,
      fontSize: size,
      lineHeight: 1.05,
      letterSpacing: '-0.005em',
      color: color || fwTokens.ink,
      fontStyle: italic ? 'italic' : 'normal',
      fontWeight: 400,
      ...style,
    }}>{children}</div>
  );
}

// Filled CTA in oxblood — the only filled button in the app where it matters
function FilledButton({ children, onClick, disabled = false, color = fwTokens.ink, fg = fwTokens.paper, style = {} }) {
  return (
    <button
      onClick={disabled ? undefined : onClick}
      disabled={disabled}
      style={{
        appearance: 'none',
        border: 0,
        width: '100%',
        padding: '16px 20px',
        background: disabled ? fwTokens.paper3 : color,
        color: disabled ? fwTokens.mute : fg,
        fontFamily: fwTokens.sans,
        fontSize: 16,
        fontWeight: 500,
        letterSpacing: '0.005em',
        borderRadius: 2,
        cursor: disabled ? 'default' : 'pointer',
        transition: 'background 200ms cubic-bezier(0.32,0.72,0,1), transform 80ms cubic-bezier(0.32,0.72,0,1)',
        ...style,
      }}
      onMouseDown={e => !disabled && (e.currentTarget.style.transform = 'scale(0.99)')}
      onMouseUp={e => (e.currentTarget.style.transform = 'scale(1)')}
      onMouseLeave={e => (e.currentTarget.style.transform = 'scale(1)')}
    >{children}</button>
  );
}

// Outline / ghost button
function OutlineButton({ children, onClick, style = {} }) {
  return (
    <button
      onClick={onClick}
      style={{
        appearance: 'none',
        width: '100%',
        padding: '16px 20px',
        background: 'transparent',
        color: fwTokens.ink,
        fontFamily: fwTokens.sans,
        fontSize: 16,
        fontWeight: 500,
        border: `1px solid ${fwTokens.ink}`,
        borderRadius: 2,
        cursor: 'pointer',
        transition: 'background 160ms cubic-bezier(0.32,0.72,0,1)',
        ...style,
      }}
      onMouseEnter={e => (e.currentTarget.style.background = 'rgba(26,23,20,0.04)')}
      onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}
    >{children}</button>
  );
}

// Section header — micro label · hairline rule · optional action
function SectionHeader({ label, action }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '0 0 10px',
    }}>
      <Micro>{label}</Micro>
      <div style={{ flex: 1, height: 1, background: fwTokens.rule }} />
      {action}
    </div>
  );
}

// Breathing canvas — reused on warmup, drafting, stitching
// 16s cycle: 4 inhale → 4 hold → 4 exhale → 4 hold
function BreathingCanvas({ size = 120, color = fwTokens.paper, label = true, light = false }) {
  const [phase, setPhase] = React.useState('inhale');
  React.useEffect(() => {
    const phases = [
      { name: 'inhale',  dur: 4000 },
      { name: 'hold-in', dur: 4000 },
      { name: 'exhale',  dur: 4000 },
      { name: 'hold-out',dur: 4000 },
    ];
    let i = 0;
    setPhase(phases[i].name);
    const tick = () => {
      i = (i + 1) % phases.length;
      setPhase(phases[i].name);
    };
    const id = setInterval(tick, 4000);
    return () => clearInterval(id);
  }, []);

  const scale =
    phase === 'inhale'   ? 1.0 :
    phase === 'hold-in'  ? 1.0 :
    phase === 'exhale'   ? 0.46 :
    /* hold-out */         0.46;

  const word =
    phase === 'inhale'   ? 'Breathe in…' :
    phase === 'hold-in'  ? 'Hold' :
    phase === 'exhale'   ? 'Breathe out…' :
                           'Hold';

  // The dot row showing current cycle position (5 cycles = 5 dots; we just animate a moving one)
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 28 }}>
      <div style={{
        width: size, height: size, position: 'relative',
        display: 'grid', placeItems: 'center',
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          border: `1px solid ${light ? fwTokens.ink : color}`,
          opacity: 0.35,
        }} />
        <div style={{
          width: size, height: size,
          background: light ? 'rgba(26,23,20,0.04)' : 'rgba(253,246,227,0.06)',
          border: `1px solid ${light ? fwTokens.ink2 : color}`,
          transform: `scale(${scale})`,
          transformOrigin: 'center',
          transition: 'transform 3800ms cubic-bezier(0.45,0,0.55,1)',
        }} />
      </div>
      {label && (
        <div style={{
          fontFamily: fwTokens.serif,
          fontSize: 22,
          fontStyle: 'italic',
          color: light ? fwTokens.ink2 : 'rgba(253,246,227,0.85)',
          minHeight: 28,
        }}>{word}</div>
      )}
    </div>
  );
}

// Audio meter — five tiny capsules that pulse
function AudioMeter({ active = true, dark = false }) {
  const [pulse, setPulse] = React.useState([0, 0, 0, 0, 0]);
  React.useEffect(() => {
    if (!active) { setPulse([0,0,0,0,0]); return; }
    const id = setInterval(() => {
      setPulse(p => [
        Math.random() * 0.7 + 0.3,
        Math.random() * 0.9 + 0.1,
        Math.random() * 1.0,
        Math.random() * 0.9 + 0.1,
        Math.random() * 0.6 + 0.2,
      ]);
    }, 140);
    return () => clearInterval(id);
  }, [active]);

  const baseColor = dark ? 'rgba(253,246,227,0.25)' : 'rgba(26,23,20,0.18)';
  const activeColor = dark ? 'rgba(253,246,227,0.9)' : fwTokens.ink;

  return (
    <div style={{ display: 'flex', gap: 6, alignItems: 'center', height: 12 }}>
      {pulse.map((p, i) => (
        <div key={i} style={{
          width: 18, height: 2,
          background: active ? activeColor : baseColor,
          opacity: active ? (0.3 + p * 0.7) : 1,
          transition: 'opacity 120ms linear',
        }} />
      ))}
    </div>
  );
}

// Status dot for sentence-map and per-line indicators
function StatusDot({ state = 'idle' }) {
  // idle: hollow, recorded: filled ink, skipped: dash, current: oxblood filled
  const common = { width: 8, height: 8, borderRadius: 0, display: 'inline-block' };
  if (state === 'recorded')
    return <span style={{ ...common, background: fwTokens.ink }} />;
  if (state === 'current')
    return <span style={{ ...common, background: fwTokens.oxblood }} />;
  if (state === 'skipped')
    return <span style={{ ...common, height: 1, marginTop: 4, background: fwTokens.mute }} />;
  return <span style={{ ...common, border: `1px solid ${fwTokens.mute}`, width: 6, height: 6 }} />;
}

// Toast — quiet status line
function Toast({ children, visible }) {
  return (
    <div style={{
      position: 'absolute',
      left: 0, right: 0, bottom: 60,
      display: 'flex', justifyContent: 'center',
      pointerEvents: 'none',
      opacity: visible ? 1 : 0,
      transform: visible ? 'translateY(0)' : 'translateY(6px)',
      transition: 'opacity 240ms cubic-bezier(0.32,0.72,0,1), transform 240ms cubic-bezier(0.32,0.72,0,1)',
      zIndex: 100,
    }}>
      <div style={{
        fontFamily: fwTokens.mono,
        fontSize: 11,
        letterSpacing: '0.1em',
        textTransform: 'uppercase',
        color: fwTokens.paper,
        background: fwTokens.ink,
        padding: '8px 14px',
      }}>{children}</div>
    </div>
  );
}

// A hairline "+" close glyph
function CloseGlyph({ color = fwTokens.ink, size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 14 14">
      <path d="M1 1 L13 13 M13 1 L1 13" stroke={color} strokeWidth="1.2" />
    </svg>
  );
}

function ChevronBack({ color = fwTokens.ink, size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 14 14">
      <path d="M9 1 L3 7 L9 13" stroke={color} strokeWidth="1.2" fill="none" />
    </svg>
  );
}

Object.assign(window, {
  fwTokens, FWMark, Micro, Serif, FilledButton, OutlineButton,
  SectionHeader, BreathingCanvas, AudioMeter, StatusDot, Toast,
  CloseGlyph, ChevronBack,
});
