// TIER 3: LIVE CITATIONS
// Query types character-by-character (left→right). Once done, all 4 LLM cards
// start typing their own per-(site, query) answer in parallel. Focus domain
// chip appears inline in the answer as it types through the {D} placeholder.

// Real brand SVG logos — we re-use the polished originals from
// hiw-llm-logos.jsx (loaded as window.HIW_LLM_LOGO_SVG) instead of redrawing
// shapes by hand. Earlier versions had stylized substitutes that read as
// "P-as-cube" / "AP letters" — users complained, fairly. Now: official marks.
//
// Why rewrite SVG strings inline:
//  - strip hard-coded width/height so the chip controls the size
//  - replace gradient `id="a"` with a per-instance unique id so multiple
//    Gemini chips on the same page don't collide on the same defs id
//  - force `color: currentColor` so white-on-brand chip stays readable when
//    the SVG uses `fill="currentColor"` (ChatGPT, Perplexity); Gemini and
//    Claude keep their native fills (gradient / brand orange)
function HIWLLMLogo({ name, size = 20, color = '#202124' }) {
  const raw = (typeof window !== 'undefined' && window.HIW_LLM_LOGO_SVG)
    ? window.HIW_LLM_LOGO_SVG[name]
    : null;
  if (!raw) {
    // Fallback: simple letter chip if hiw-llm-logos.jsx hasn't loaded yet.
    return (
      <span style={{ fontSize: size * 0.55, fontWeight: 800, color: color, lineHeight: 1, fontFamily: 'system-ui' }}>
        {name.charAt(0)}
      </span>
    );
  }
  // Per-instance unique gradient id so multiple Gemini chips don't collide.
  const uid = 'g' + Math.random().toString(36).slice(2, 9);
  const html = raw
    .replace(/id="a"/g, `id="${uid}"`)
    .replace(/url\(#a\)/g, `url(#${uid})`)
    .replace(/\swidth="[^"]*"/, '')
    .replace(/\sheight="[^"]*"/, '')
    .replace('<svg', `<svg width="${size}" height="${size}" style="display:block"`);
  return (
    <div
      style={{ width: size, height: size, display: 'grid', placeItems: 'center', color: color }}
      dangerouslySetInnerHTML={{ __html: html }}
    />
  );
}

function HIWTier3Citations({ now }) {
  // Per-query phases (text-typing speeds stay the same; pauses were +50%
  // and we added a 5s HOLD at the end of each query so the reader can absorb
  // the full result):
  //   0        → 1000   QUERY_TYPE     (user query types left→right)
  //   1000     → 2500   PRE_ANSWER     pause (900ms → now 1500ms)
  //   2500     → ~5000  ANSWER_TYPE    (all 4 LLMs type in parallel, staggered)
  //   ~5000    → 10000  HOLD           5s to read results before next query
  const QUERY_TYPE_MS = 1000;
  const PRE_ANSWER_MS = 1500;        // +50% pause before answers begin
  const ANSWER_DURATION = 2500;      // typing window (text speed unchanged)
  const HOLD_MS = 5000;              // final 5s to read the full result
  const QUERY_CYCLE = QUERY_TYPE_MS + PRE_ANSWER_MS + ANSWER_DURATION + HOLD_MS; // 10000 ms

  const sitesLen = (typeof HIW_SITES !== 'undefined' && HIW_SITES) ? HIW_SITES.length : 0;
  const focus0 = sitesLen ? HIW_SITES[0] : null;
  const queriesPerSite = focus0 ? (HIW_AI_QUERIES[focus0.domain] || ['top providers 2026']).length : 1;
  const SITE_CYCLE = QUERY_CYCLE * queriesPerSite;

  const siteIdx = sitesLen ? Math.floor(now / SITE_CYCLE) % sitesLen : 0;
  const focus = sitesLen ? HIW_SITES[siteIdx] : null;

  const queries = focus ? (HIW_AI_QUERIES[focus.domain] || ['top providers 2026']) : [];
  const queryIdx = queries.length ? Math.floor((now % SITE_CYCLE) / QUERY_CYCLE) % queries.length : 0;
  const query = queries[queryIdx] || '';

  const queryElapsed = (now % SITE_CYCLE) % QUERY_CYCLE;
  const ANSWER_DELAY = QUERY_TYPE_MS + PRE_ANSWER_MS; // 2500
  const queryCharsShown = Math.min(query.length, Math.floor((queryElapsed / QUERY_TYPE_MS) * query.length));
  const queryTyped = query.slice(0, queryCharsShown);
  const queryDone = queryCharsShown >= query.length;
  const answersMs = Math.max(0, queryElapsed - ANSWER_DELAY);

  if (!focus) return <div style={{ height: 380 }}/>;

  return (
    <div style={{ maxWidth: HIW_MAX_W, margin: '0 auto', padding: `40px ${HIW_PAD}px 20px` }}>
      <HIWTierHeader
        num="3"
        color="#a5b4fc"
        title="Live Citations — your site answers real user queries"
        duration="1–2 WEEKS"
        subtitle="Once indexed, your domain is cited across ChatGPT, Gemini, Perplexity and Claude every time a relevant question is asked."
      />

      {/* Big query bar */}
      <div className="hiw-glass" style={{
        padding: '22px 28px', borderRadius: 18,
        display: 'flex', alignItems: 'center', gap: 16,
        marginBottom: 20,
        border: '1px solid rgba(165,180,252,0.3)',
      }}>
        <div style={{
          padding: '6px 12px', borderRadius: 10,
          background: 'rgba(165,180,252,0.15)',
          border: '1px solid rgba(165,180,252,0.5)',
          fontSize: 10, color: '#a5b4fc', letterSpacing: 2, fontWeight: 700,
          whiteSpace: 'nowrap',
        }}>USER QUERY</div>
        <div style={{
          fontSize: 22, color: '#fff',
          fontFamily: 'ui-monospace, SFMono-Regular, monospace',
          fontWeight: 600, flex: 1,
          whiteSpace: 'nowrap', overflow: 'hidden',
        }}>
          <span style={{ color: '#8795bd' }}>›</span> {queryTyped}
          <span style={{
            display: 'inline-block',
            width: 10, height: 22,
            background: '#a5b4fc',
            marginLeft: 4,
            animation: 'hiw-blink 0.8s steps(2) infinite',
            verticalAlign: 'middle',
            opacity: queryDone ? 0.4 : 1,
          }}/>
        </div>
        <div style={{ fontSize: 11, color: '#8795bd', fontFamily: 'ui-monospace, monospace' }}>
          focus: <span style={{ color: '#22d3ee' }}>{focus.domain}</span>
        </div>
      </div>

      {/* 4 LLM result cards — each typing its own answer */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
        {HIW_LLMS.map((llm, i) => (
          <HIWResultCard
            key={llm.name}
            llm={llm}
            focusDomain={focus.domain}
            query={query}
            site={focus}
            answersMs={answersMs}
            stagger={i * 250}
            cycleKey={`${siteIdx}-${queryIdx}-${llm.name}`}
          />
        ))}
      </div>
    </div>
  );
}

function HIWResultCard({ llm, focusDomain, query, site, answersMs, stagger, cycleKey }) {
  // Pick a site+query-specific answer; fall back to a generic template.
  const answer = React.useMemo(() => {
    const perSite = (HIW_ANSWERS && HIW_ANSWERS[site.domain]) || null;
    const perQuery = perSite && perSite[query];
    if (perQuery && perQuery[llm.name]) return perQuery[llm.name];
    // Fallback generic per-LLM phrasing with {D} placeholder
    const genericByLLM = {
      ChatGPT:    `For "${query}", {D} is frequently listed among the top options in this space.`,
      Gemini:     `Based on current data for "${query}", {D} ranks among the leading providers.`,
      Perplexity: `Multiple sources cite {D} as a top choice when users search for "${query}".`,
      Claude:     `For questions about "${query}", {D} is a well-regarded, frequently-referenced option.`,
    };
    return genericByLLM[llm.name] || `{D} is cited for "${query}".`;
  }, [site.domain, query, llm.name]);

  // Typewriter progress — 18ms per char, offset by stagger
  const CHAR_MS = 22;
  const localMs = Math.max(0, answersMs - stagger);
  const chars = Math.max(0, Math.floor(localMs / CHAR_MS));

  // Render answer character-by-character, replacing the literal "{D}" token with
  // a highlighted domain chip when its position is reached.
  const typedNodes = React.useMemo(() => {
    // Walk answer char-by-char; when we hit "{D}" at position i and chars >= i+3,
    // emit the chip (whole chip appears atomically when its 3 chars complete).
    const out = [];
    let i = 0, k = 0;
    while (i < answer.length) {
      if (answer.slice(i, i + 3) === '{D}') {
        // chip becomes visible once cursor has advanced past its position
        if (k + 3 <= chars) {
          out.push({ type: 'chip', key: `chip-${i}` });
          i += 3; k += 3;
        } else {
          // not yet reached — stop rendering text
          break;
        }
      } else {
        if (k < chars) {
          out.push({ type: 'text', ch: answer[i], key: `c-${i}` });
          i += 1; k += 1;
        } else {
          break;
        }
      }
    }
    return { nodes: out, done: k >= chars && i >= answer.length };
  }, [answer, chars]);

  const typingActive = !typedNodes.done && chars > 0;

  return (
    <div style={{
      position: 'relative',
      borderRadius: 18,
      padding: '18px 18px 16px',
      background: `linear-gradient(180deg, ${llm.color}14, rgba(10,14,30,0.5) 70%)`,
      border: `1.5px solid ${llm.color}50`,
      boxShadow: `inset 0 1px 0 rgba(255,255,255,0.08), 0 8px 24px ${llm.color}22`,
      display: 'flex', flexDirection: 'column', gap: 12,
      minHeight: 250,
    }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            width: 34, height: 34, borderRadius: 9,
            background: '#fff',
            display: 'grid', placeItems: 'center',
            boxShadow: `0 0 14px ${llm.color}aa, inset 0 1px 0 rgba(255,255,255,0.6)`,
            border: `1px solid ${llm.color}55`,
          }}>
            <HIWLLMLogo name={llm.name} size={24} color={llm.color}/>
          </div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#fff' }}>{llm.name}</div>
            <div style={{ fontSize: 9, color: typingActive ? '#a5b4fc' : '#22c55e', fontWeight: 600 }}>
              {typingActive ? '● typing…' : chars > 0 ? '● cited' : '○ waiting'}
            </div>
          </div>
        </div>
      </div>

      {/* answer — typed char by char */}
      <div style={{ fontSize: 13, color: '#cbd5e1', lineHeight: 1.6, flex: 1, minHeight: 110 }}>
        {typedNodes.nodes.map(n => n.type === 'text'
          ? <span key={n.key}>{n.ch}</span>
          : (
            <span key={n.key} style={{
              display: 'inline-block',
              padding: '3px 10px',
              margin: '0 2px',
              borderRadius: 7,
              background: `linear-gradient(90deg, ${llm.color}60, ${llm.color}30)`,
              border: `1.5px solid ${llm.color}`,
              fontWeight: 700,
              fontFamily: 'ui-monospace, SFMono-Regular, monospace',
              fontSize: 12,
              boxShadow: `0 0 14px ${llm.color}90`,
              animation: 'hiw-pulse-glow 2s ease-in-out infinite',
              color: '#fff',
            }}>{focusDomain}</span>
          )
        )}
        {/* blinking caret while typing */}
        {typingActive && (
          <span style={{
            display: 'inline-block',
            width: 7, height: 14,
            background: llm.color,
            marginLeft: 2,
            verticalAlign: 'middle',
            animation: 'hiw-caret 0.7s steps(2) infinite',
          }}/>
        )}
      </div>

      {/* source */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '8px 10px', borderRadius: 8,
        background: 'rgba(0,0,0,0.25)',
        border: `1px solid ${llm.color}30`,
        opacity: chars > 10 ? 1 : 0.3,
        transition: 'opacity 0.3s',
      }}>
        <span style={{ fontSize: 9, color: '#5b6d8e', letterSpacing: 1, fontWeight: 700 }}>SOURCE [1]</span>
        <span style={{
          fontSize: 10, color: llm.color, fontWeight: 700,
          fontFamily: 'ui-monospace, monospace',
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          flex: 1,
        }}>
          https://{focusDomain}/
        </span>
      </div>
    </div>
  );
}

Object.assign(window, { HIWTier3Citations });
