// Shared marketing chrome: Nav + Footer + CTABand
// Expects logo asset at assets/logo-horizontal.svg relative to page

// TODO: change APP_URL to production URL when prod app is deployed
const APP_URL = 'https://app-dev.robotdogs.tech/';
// Sign-in jumps straight into Microsoft OAuth (PKCE) — no app landing page.
// Trial goes straight to the public signup form — no auth required.
const SIGNUP_URL = APP_URL + 'signup';
const SIGNIN_URL = APP_URL + 'api/auth/signin';

// Expose globally so per-page scripts can use the same URLs
window.APP_URL = APP_URL;
window.SIGNUP_URL = SIGNUP_URL;
window.SIGNIN_URL = SIGNIN_URL;

const NAV_LINKS = [
  { href: 'product', label: 'Product' },
  { href: 'for-msps', label: 'For MSPs' },
  { href: 'security', label: 'Security' },
  { href: 'pricing', label: 'Pricing' },
];

function MkNav() {
  return (
    <header className="mk-nav">
      <div className="mk-container mk-nav-inner">
        <a href="index.html" className="mk-nav-logo">
          <img src="logo-horizontal.svg" alt="Robot Dogs"/>
        </a>
        <nav className="mk-nav-links">
          {NAV_LINKS.map(l => (
            <a key={l.label} href={l.href}>{l.label}</a>
          ))}
        </nav>
        <div className="mk-nav-right">
          <a href={SIGNIN_URL} className="mk-btn mk-btn-ghost">Sign in</a>
          <a href={SIGNUP_URL} className="mk-btn mk-btn-cta">Start 7-day trial</a>
        </div>
      </div>
    </header>
  );
}

function MkFooter() {
  return (
    <footer className="mk-footer">
      <div className="mk-container">
        <div className="mk-footer-grid">
          <div>
            <img src="logo-horizontal-dark.svg" style={{height:26, marginBottom:14}} alt=""/>
            <p style={{margin:0, maxWidth:280, lineHeight:1.6}}>
              Continuous security reviews and live support for Microsoft 365 and Azure.
            </p>
          </div>
          <div>
            <h4>Product</h4>
            <ul>
              <li><a href="product">Security Review</a></li>
              <li><a href="product">Drift Monitor</a></li>
              <li><a href="product">AI Assistant</a></li>
              <li><a href="pricing">Pricing</a></li>
            </ul>
          </div>
          <div>
            <h4>Solutions</h4>
            <ul>
              <li><a href="for-msps">For MSPs</a></li>
              <li><a href="#">For IT teams</a></li>
              <li><a href="#">Integrations</a></li>
            </ul>
          </div>
          <div>
            <h4>Company</h4>
            <ul>
              <li><a href="#">About</a></li>
              <li><a href="#">Changelog</a></li>
              <li><a href="#">Contact</a></li>
            </ul>
          </div>
          <div>
            <h4>Trust</h4>
            <ul>
              <li><a href="security">Security</a></li>
              <li><a href="#">Privacy</a></li>
              <li><a href="#">Terms</a></li>
              <li><a href="#">Status</a></li>
            </ul>
          </div>
        </div>
        <div className="mk-footer-bottom">
          <span>© 2026 Robot Dogs, Inc.</span>
          <span style={{marginLeft:'auto'}}>Made for admins who have too much to do.</span>
        </div>
      </div>
    </footer>
  );
}

function MkCTABand({ primaryCTA = 'Start 7-day trial' }) {
  return (
    <section className="mk-section-slate mk-section-tight" style={{position:'relative', overflow:'hidden'}}>
      <div className="mk-hero-grid"/>
      <div className="mk-container" style={{textAlign:'center', position:'relative', zIndex:1}}>
        <h2 className="mk-display mk-h2" style={{color:'#fff', margin:'0 0 14px'}}>
          Seven days. No card. No demo call.
        </h2>
        <p className="mk-lede" style={{color:'#b8c1d4', margin:'0 0 24px', maxWidth:600, marginLeft:'auto', marginRight:'auto'}}>
          Connect a tenant in 90 seconds and see what Robot Dogs finds. If it's not for you, walk away.
        </p>
        <a href={SIGNUP_URL} className="mk-btn mk-btn-cta mk-btn-lg">{primaryCTA} →</a>
      </div>
    </section>
  );
}

Object.assign(window, { MkNav, MkFooter, MkCTABand });

// =============================================================
// Help bubble — chat widget rendered on every marketing page.
// Hides itself when /api/status reports the daily ceiling has been hit.
// =============================================================

function MkHelpBubble() {
  const { useState, useEffect, useRef } = React;
  const [open, setOpen] = useState(false);
  const [available, setAvailable] = useState(null); // null = unknown, false = ceiling hit, true = open
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [streaming, setStreaming] = useState(false);
  const [closedDuringSession, setClosedDuringSession] = useState(false);
  const scrollRef = useRef(null);
  const inputRef = useRef(null);

  useEffect(() => {
    let cancelled = false;
    fetch('/api/status', { method: 'GET' })
      .then(r => r.ok ? r.json() : { open: false })
      .then(data => { if (!cancelled) setAvailable(!!data.open); })
      .catch(() => { if (!cancelled) setAvailable(false); });
    return () => { cancelled = true; };
  }, []);

  useEffect(() => {
    if (open && inputRef.current) inputRef.current.focus();
  }, [open]);

  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages, streaming]);

  if (available !== true && !open) return null;
  if (available === false && messages.length === 0) return null;

  const send = async () => {
    const text = input.trim();
    if (!text || streaming || closedDuringSession) return;
    setInput('');
    const newHistory = [...messages, { role: 'user', content: text }];
    setMessages([...newHistory, { role: 'assistant', content: '' }]);
    setStreaming(true);

    try {
      const res = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: text, history: messages }),
      });
      if (!res.ok || !res.body) {
        throw new Error('http ' + res.status);
      }
      const reader = res.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';
      let assistant = '';
      while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });
        const events = buffer.split('\n\n');
        buffer = events.pop() ?? '';
        for (const ev of events) {
          if (!ev.trim()) continue;
          let name = 'message', dataStr = '';
          for (const line of ev.split('\n')) {
            if (line.startsWith('event: ')) name = line.slice(7).trim();
            else if (line.startsWith('data: ')) dataStr += line.slice(6);
          }
          if (!dataStr) continue;
          let data;
          try { data = JSON.parse(dataStr); } catch { continue; }
          if (name === 'chunk' && data.text) {
            assistant += data.text;
            setMessages([...newHistory, { role: 'assistant', content: assistant }]);
          } else if (name === 'done') {
            if (data.closed) setClosedDuringSession(true);
          }
        }
      }
    } catch (err) {
      setMessages([...newHistory, { role: 'assistant', content: "Sorry — I couldn't reach the chat right now. Try again, or email hello@robotdogs.tech." }]);
    } finally {
      setStreaming(false);
    }
  };

  const onKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      send();
    }
  };

  const bubble = (
    <button
      type="button"
      onClick={() => setOpen(true)}
      aria-label="Open chat"
      style={{
        position: 'fixed', bottom: 22, right: 22, width: 56, height: 56,
        borderRadius: '50%', border: 'none', background: '#3B6FF5',
        color: '#fff', cursor: 'pointer', display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 8px 24px rgba(59,111,245,0.45)', zIndex: 1000,
      }}
    >
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
      </svg>
    </button>
  );

  if (!open) return bubble;

  const greeting = "Hi — I can answer questions about Robot Dogs. Pricing, plans, what we monitor, anything else.";

  return (
    <div style={{
      position: 'fixed', bottom: 22, right: 22, width: 360, height: 520,
      maxWidth: 'calc(100vw - 32px)', maxHeight: 'calc(100vh - 64px)',
      background: '#fff', borderRadius: 16, overflow: 'hidden',
      boxShadow: '0 24px 64px rgba(20,24,40,0.32)', zIndex: 1000,
      display: 'flex', flexDirection: 'column',
      fontFamily: 'Inter, system-ui, sans-serif',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', background: '#1A1F36', color: '#fff' }}>
        <span style={{ fontWeight: 600, fontSize: 14 }}>Robot Dogs</span>
        <button type="button" onClick={() => setOpen(false)} aria-label="Close" style={{ background: 'transparent', border: 'none', color: '#fff', cursor: 'pointer', fontSize: 18, padding: 0 }}>×</button>
      </div>
      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
        {messages.length === 0 ? (
          <div style={{ background: '#F3F5FA', color: '#1A1F36', padding: '10px 12px', borderRadius: 12, fontSize: 14, lineHeight: 1.5 }}>
            {greeting}
          </div>
        ) : messages.map((m, i) => (
          <div key={i} style={{
            alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start',
            background: m.role === 'user' ? '#3B6FF5' : '#F3F5FA',
            color: m.role === 'user' ? '#fff' : '#1A1F36',
            padding: '8px 12px', borderRadius: 12, maxWidth: '85%',
            fontSize: 14, whiteSpace: 'pre-wrap', lineHeight: 1.5,
          }}>{m.content || (streaming && i === messages.length - 1 ? '…' : '')}</div>
        ))}
      </div>
      <div style={{ padding: 12, borderTop: '1px solid #E5E7EB', background: '#FAFBFD' }}>
        <textarea
          ref={inputRef}
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={onKey}
          placeholder={closedDuringSession ? 'Chat ended for the day' : 'Ask anything…'}
          rows={2}
          disabled={streaming || closedDuringSession}
          style={{ width: '100%', border: '1px solid #D1D5DB', borderRadius: 8, padding: '8px 10px', fontSize: 14, resize: 'none', boxSizing: 'border-box', fontFamily: 'inherit' }}
        />
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 6 }}>
          <button type="button" onClick={send} disabled={streaming || closedDuringSession || !input.trim()} style={{ background: '#3B6FF5', color: '#fff', border: 'none', padding: '6px 14px', borderRadius: 6, fontSize: 13, fontWeight: 500, cursor: streaming || closedDuringSession ? 'default' : 'pointer', opacity: streaming || closedDuringSession || !input.trim() ? 0.55 : 1 }}>Send</button>
        </div>
        <p style={{ fontSize: 11, color: '#9CA3AF', margin: '6px 0 0', textAlign: 'center' }}>
          AI assistant — for sales/support email hello@robotdogs.tech
        </p>
      </div>
    </div>
  );
}

window.MkHelpBubble = MkHelpBubble;

// Self-mount the bubble on every marketing page. Adds its own root element to
// document.body so it's independent of the page's #root.
(function mountHelpBubble() {
  if (document.getElementById('mk-help-bubble-root')) return;
  const root = document.createElement('div');
  root.id = 'mk-help-bubble-root';
  document.body.appendChild(root);
  // Defer rendering until React/ReactDOM are available (they load async via UMD).
  const tryMount = () => {
    if (!window.React || !window.ReactDOM) {
      requestAnimationFrame(tryMount);
      return;
    }
    const reactRoot = window.ReactDOM.createRoot(root);
    reactRoot.render(<MkHelpBubble/>);
  };
  tryMount();
})();
