/* global React */
/* ============================================================
   Shared components for Home Service CTO
   Attached to window at bottom.
   ============================================================ */

const { useState, useEffect, useRef, useCallback, useMemo } = React;

/* ---------- Logos ---------- */

function LogoWordmark({ size = 24, showCursor = true }) {
  return (
    <span className="logo-wordmark glow" style={{ fontSize: size }}>
      <span className="bracket" style={{ color: 'var(--fg-bright)' }}>&gt;</span>
      <span style={{ color: 'var(--fg-bright)' }}>HomeService</span>
      <span className="slash">/</span>
      <span style={{ color: 'var(--accent)' }}>CTO</span>
      {showCursor && <span className="cursor thin" style={{ height: '0.9em' }} />}
    </span>
  );
}

function LogoMonogram({ size = 48 }) {
  return (
    <span
      className="logo-crt glow"
      style={{ width: size * 1.35, height: size, fontSize: size * 0.38 }}
    >
      HS·CTO
    </span>
  );
}

// 8-bit wrench — horizontal open-end wrench, unmistakable silhouette
function LogoPixel({ scale = 3 }) {
  // 16 wide × 10 tall
  const art = [
    "................",
    "..##............",
    ".####...........",
    "##..##..........",
    "##..############",
    "##..############",
    "##..##..........",
    ".####...........",
    "..##............",
    "................",
  ];
  const px = scale;
  return (
    <span
      style={{
        display: 'inline-grid',
        gridTemplateColumns: `repeat(16, ${px}px)`,
        gridAutoRows: `${px}px`,
        gap: 0,
      }}
      aria-label="Home Service CTO wrench mark"
    >
      {art.join('').split('').map((c, i) => (
        <span
          key={i}
          style={{
            background: c === '#' ? 'var(--fg)' : 'transparent',
          }}
        />
      ))}
    </span>
  );
}

function LogoFull({ size = 22 }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center' }}>
      <LogoWordmark size={size} />
    </span>
  );
}

/* ---------- Mascot: "Ctrl" the CRT ---------- */

function Mascot({ size = 120, expression = 'smile', speech = null }) {
  // 14 × 14 pixel mascot — CRT with legs and a face
  const faces = {
    smile:  ['.#.....#.', '.........', '.##...##.', '...###...'],
    wink:   ['.#.....#.', '.........', '.##...---', '...###...'],
    think:  ['.#.....#.', '.........', '.........', '..#####..'],
    happy:  ['.#.....#.', '.........', '.##...##.', '..#####..'],
  };
  // 13-wide face rows (we'll center inside)
  const face = faces[expression] || faces.smile;
  // Full body frame — simplified pixel grid 14x16
  // # = body outline, . = empty, @ = screen glow, F = face pixel
  const body = [
    "..############",
    "..#..........#",
    "..#.@@@@@@@@.#",  // screen top
    "..#.@FFFFFFF@#",
    "..#.@FFFFFFF@#",
    "..#.@FFFFFFF@#",
    "..#.@FFFFFFF@#",
    "..#.@@@@@@@@.#",
    "..#..........#",
    "..############",
    "..##........##",  // base
    ".##..........##",
    "##............##",
    "#..............#",
    "#.##........##.#", // feet
    ".##..........##.",
  ];

  // overlay face into the @F rows using rows 3-6 of face expression
  const faceRows = face; // 4 rows of 9 chars each representing what's inside screen
  const mapped = body.map((row, i) => {
    if (i >= 3 && i <= 6) {
      const fr = faceRows[i - 3] || '.........';
      // row is 14 chars — positions 4..12 (9 chars) are @FFFFFFF@ inner area
      return row.split('').map((c, j) => {
        if (j >= 4 && j <= 12 && fr[j - 4]) {
          const f = fr[j - 4];
          if (f === '#') return 'X'; // face pixel
          return 'S'; // screen background
        }
        return c;
      }).join('');
    }
    return row;
  });

  const px = size / 14;
  return (
    <div style={{ display: 'inline-flex', alignItems: 'flex-end', gap: '0.75em' }}>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: `repeat(14, ${px}px)`,
          gridAutoRows: `${px}px`,
        }}
      >
        {mapped.join('').split('').map((c, i) => {
          let bg = 'transparent';
          if (c === '#') bg = 'var(--fg)';
          else if (c === 'S') bg = 'var(--bg-3)';
          else if (c === 'X') bg = 'var(--fg-bright)';
          return <span key={i} style={{ background: bg }} />;
        })}
      </div>
      {speech && (
        <div
          style={{
            position: 'relative',
            border: '1px solid var(--fg)',
            padding: '0.5em 0.8em',
            background: 'var(--bg-2)',
            maxWidth: 280,
            fontSize: 13,
            color: 'var(--fg-bright)',
          }}
        >
          {speech}
          <span
            style={{
              position: 'absolute',
              left: -6,
              top: 18,
              width: 10,
              height: 10,
              background: 'var(--bg-2)',
              borderLeft: '1px solid var(--fg)',
              borderBottom: '1px solid var(--fg)',
              transform: 'rotate(45deg)',
            }}
          />
        </div>
      )}
    </div>
  );
}

/* ---------- CRT frame wrapper ---------- */

function CRTFrame({ title = null, children, actions = null, style = {} }) {
  return (
    <div className="crt-frame" style={{
      border: '1px solid var(--border)',
      background: 'var(--bg)',
      ...style
    }}>
      {title && (
        <div style={{
          borderBottom: '1px dashed var(--border)',
          padding: '0.4em 0.8em',
          fontSize: 11,
          letterSpacing: '0.2em',
          textTransform: 'uppercase',
          color: 'var(--fg-dim)',
        }}>
          {title}
        </div>
      )}
      <div style={{ padding: '1.25rem 1.5rem' }}>{children}</div>
    </div>
  );
}

/* ---------- ASCII divider ---------- */

function AsciiRule({ char = '─', label = null }) {
  return (
    <div className="ascii-rule" style={{ display: 'flex', alignItems: 'center', gap: '0.5em', margin: '2rem 0' }}>
      <span style={{ flex: 1, overflow: 'hidden' }}>{char.repeat(400)}</span>
      {label && (
        <>
          <span style={{ color: 'var(--fg-dim)', fontSize: 11, letterSpacing: '0.2em' }}>{label}</span>
          <span style={{ flex: 1, overflow: 'hidden' }}>{char.repeat(400)}</span>
        </>
      )}
    </div>
  );
}

/* ---------- Typewriter ---------- */

function Typewriter({ text, speed = 22, onDone, className = '' }) {
  const [shown, setShown] = useState('');
  useEffect(() => {
    setShown('');
    let i = 0;
    const tick = () => {
      i++;
      setShown(text.slice(0, i));
      if (i < text.length) {
        timer = setTimeout(tick, speed);
      } else if (onDone) {
        onDone();
      }
    };
    let timer = setTimeout(tick, speed);
    return () => clearTimeout(timer);
  }, [text, speed]);
  return <span className={className}>{shown}</span>;
}

/* ---------- Header nav ---------- */

function Header({ current = 'home' }) {
  const links = [
    { id: 'home',      label: 'home',      href: 'index.html' },
    { id: 'services',  label: 'services',  href: 'index.html#services' },
    { id: 'process',   label: 'process',   href: 'index.html#process' },
    { id: 'pricing',   label: 'pricing',   href: 'index.html#pricing' },
    { id: 'about',     label: 'about',     href: 'index.html#about' },
    { id: 'contact',   label: 'contact',   href: 'index.html#contact' },
  ];
  const [open, setOpen] = React.useState(false);
  const [isMobile, setIsMobile] = React.useState(
    typeof window !== 'undefined' ? window.innerWidth < 900 : false
  );
  React.useEffect(() => {
    const onResize = () => setIsMobile(window.innerWidth < 900);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  React.useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const linkStyle = (active) => ({
    color: active ? 'var(--fg-bright)' : 'var(--fg-dim)',
    borderBottom: active ? '1px solid var(--fg)' : '1px dashed transparent',
    fontSize: 13,
    letterSpacing: '0.1em',
    textTransform: 'uppercase',
    paddingBottom: 2,
  });

  return (
    <header style={{
      borderBottom: '1px solid var(--border)',
      background: 'color-mix(in oklab, var(--bg) 92%, transparent)',
      backdropFilter: 'blur(6px)',
      position: 'sticky',
      top: 0,
      zIndex: 100,
    }}>
      <div className="container" style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: isMobile ? '0.9rem 1.2rem' : '0.9rem 2rem',
        gap: '1rem',
      }}>
        <a href="index.html" style={{ border: 'none' }}>
          <LogoFull size={18} />
        </a>

        {!isMobile && (
          <nav style={{ display: 'flex', gap: '1.2rem', alignItems: 'center', flexWrap: 'wrap' }}>
            {links.map(l => (
              <a key={l.id} href={l.href} style={linkStyle(current === l.id)}>
                {current === l.id ? '> ' : ''}{l.label}
              </a>
            ))}
          </nav>
        )}

        {isMobile && (
          <button
            onClick={() => setOpen(o => !o)}
            aria-label="Toggle menu"
            aria-expanded={open}
            style={{
              background: 'transparent',
              border: '1px solid var(--border)',
              color: 'var(--fg-bright)',
              fontFamily: 'inherit',
              fontSize: 12,
              letterSpacing: '0.1em',
              textTransform: 'uppercase',
              padding: '0.5em 0.9em',
              cursor: 'pointer',
            }}
          >
            {open ? '[ × ] close' : '[ ≡ ] menu'}
          </button>
        )}
      </div>

      {isMobile && open && (
        <div
          style={{
            position: 'fixed',
            left: 0,
            right: 0,
            top: 56,
            bottom: 0,
            background: 'color-mix(in oklab, var(--bg) 96%, transparent)',
            backdropFilter: 'blur(8px)',
            zIndex: 99,
            padding: '1.5rem 1.4rem 2rem',
            overflowY: 'auto',
          }}
        >
          <div className="mono-label" style={{ marginBottom: '1rem' }}>
            § navigation
          </div>
          <nav style={{ display: 'flex', flexDirection: 'column' }}>
            {links.map(l => (
              <a
                key={l.id}
                href={l.href}
                onClick={() => setOpen(false)}
                style={{
                  color: current === l.id ? 'var(--fg-bright)' : 'var(--fg)',
                  fontSize: 17,
                  letterSpacing: '0.06em',
                  textTransform: 'uppercase',
                  padding: '0.9em 0',
                  borderBottom: '1px dashed var(--border)',
                }}
              >
                {current === l.id ? '▸ ' : '· '}{l.label}
              </a>
            ))}
          </nav>
          <a
            href="index.html#contact"
            onClick={() => setOpen(false)}
            className="btn btn-primary"
            style={{ marginTop: '1.8rem', display: 'inline-block' }}
          >
            ▸ schedule my tech stack diagnostic
          </a>
        </div>
      )}
    </header>
  );
}

/* ---------- Footer ---------- */

function Footer() {
  return (
    <footer style={{
      borderTop: '1px solid var(--border)',
      marginTop: '6rem',
      padding: '3rem 0 2rem',
      color: 'var(--fg-dim)',
      fontSize: 13,
    }}>
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: '2rem' }}>
          <div>
            <LogoFull size={16} />
            <p style={{ marginTop: '0.8em', color: 'var(--fg-dim)' }}>
              A one-person CTO shop for mid-size home service companies. Built in a garage. Stays in the garage.
            </p>
          </div>
          <div>
            <div className="mono-label" style={{ marginBottom: '0.5em' }}>services</div>
            <div>Tech Stack Audit</div>
            <div>AI Implementation</div>
            <div>Agent Build</div>
            <div>Consultation</div>
          </div>
          <div>
            <div className="mono-label" style={{ marginBottom: '0.5em' }}>contact</div>
            <div>book@homeservicecto.com</div>
            <div>(555) 010-RUNC</div>
            <div>M–F · 8a–6p CT</div>
          </div>
          <div>
            <div className="mono-label" style={{ marginBottom: '0.5em' }}>bits</div>
            <div><a href="#contact">book a call</a></div>
          </div>
        </div>
        <div style={{ marginTop: '2.5rem', display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: '1rem' }}>
          <span>© {new Date().getFullYear()} Home Service CTO · All rights reserved</span>
          <span className="muted">press <kbd>?</kbd> anywhere for the command palette</span>
        </div>
      </div>
    </footer>
  );
}

/* ---------- Expose ---------- */
Object.assign(window, {
  LogoWordmark, LogoMonogram, LogoPixel, LogoFull,
  Mascot, CRTFrame, AsciiRule, Typewriter,
  Header, Footer,
});
