// Google Fonts Pairing — 10 curated heading + body font pairs with live preview,
// editable text, font size controls, and copyable CSS.

window.TOOL_HANDLERS['google-fonts-pair'] = function GoogleFontsPairTool() {
  const PAIRS = [
    { heading: 'Playfair Display', body: 'Source Sans 3' },
    { heading: 'Roboto', body: 'Roboto Slab' },
    { heading: 'Montserrat', body: 'Merriweather' },
    { heading: 'Oswald', body: 'Lato' },
    { heading: 'Raleway', body: 'Open Sans' },
    { heading: 'Poppins', body: 'Nunito' },
    { heading: 'Lora', body: 'Poppins' },
    { heading: 'DM Serif Display', body: 'DM Sans' },
    { heading: 'Space Grotesk', body: 'Inter' },
    { heading: 'Bebas Neue', body: 'Source Sans 3' },
  ];

  const [selected, setSelected] = React.useState(null);
  const [headingText, setHeadingText] = React.useState('The quick brown fox jumps over the lazy dog');
  const [bodyText, setBodyText] = React.useState('Typography is the art and technique of arranging type to make written language legible, readable, and appealing when displayed. The arrangement of type involves selecting typefaces, point sizes, line lengths, line-spacing, and letter-spacing.');
  const [headingSize, setHeadingSize] = React.useState(40);
  const [bodySize, setBodySize] = React.useState(16);
  const [copied, setCopied] = React.useState(false);
  const [fontsLoaded, setFontsLoaded] = React.useState(false);

  // Build Google Fonts URL for all pairs
  const buildFontUrl = () => {
    const unique = new Set();
    PAIRS.forEach((p) => { unique.add(p.heading); unique.add(p.body); });
    const families = Array.from(unique).map((f) =>
      'family=' + f.replace(/ /g, '+') + ':wght@400;700'
    ).join('&');
    return `https://fonts.googleapis.com/css2?${families}&display=swap`;
  };

  // Load fonts on mount
  React.useEffect(() => {
    const url = buildFontUrl();
    const existing = document.querySelector(`link[href="${url}"]`);
    if (existing) { setFontsLoaded(true); return; }
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = url;
    link.onload = () => setFontsLoaded(true);
    document.head.appendChild(link);
  }, []);

  const pair = selected !== null ? PAIRS[selected] : null;

  const getCSSOutput = () => {
    if (!pair) return '';
    const h = pair.heading.replace(/ /g, '+');
    const b = pair.body.replace(/ /g, '+');
    return `@import url('https://fonts.googleapis.com/css2?family=${h}:wght@400;700&family=${b}:wght@400;700&display=swap');

h1, h2, h3, h4, h5, h6 {
  font-family: '${pair.heading}', serif;
  font-weight: 700;
}

body, p {
  font-family: '${pair.body}', sans-serif;
  font-weight: 400;
}`;
  };

  const copyCSS = () => {
    navigator.clipboard.writeText(getCSSOutput());
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  return (
    <div className="mini-tool">
      <style>{`
        .gfp-grid {
          display: grid; grid-template-columns: 1fr 1fr; gap: 10px;
          margin-bottom: 20px;
        }
        .gfp-card {
          padding: 16px; border-radius: 10px; cursor: pointer;
          border: 2px solid var(--id-border); background: var(--id-surface);
          transition: all 180ms ease; overflow: hidden;
        }
        .gfp-card:hover { border-color: var(--id-border-strong); background: var(--id-surface-alt); }
        .gfp-card.active { border-color: var(--id-brand-blue); background: var(--id-brand-blue-soft); }
        .gfp-card-heading {
          font-size: 20px; font-weight: 700; color: var(--id-text);
          line-height: 1.3; margin-bottom: 6px;
          white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
        }
        .gfp-card-body {
          font-size: 13px; color: var(--id-text-muted); line-height: 1.5;
          display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;
          overflow: hidden;
        }
        .gfp-card-meta {
          display: flex; gap: 4px; flex-wrap: wrap; margin-top: 8px;
        }
        .gfp-card-tag {
          font-size: 10px; font-weight: 600; text-transform: uppercase;
          letter-spacing: 0.04em; padding: 2px 8px; border-radius: 4px;
          background: var(--id-surface-sunken); color: var(--id-text-muted);
        }
        .gfp-detail {
          border: 1px solid var(--id-border); border-radius: 12px;
          background: var(--id-surface); overflow: hidden;
          margin-bottom: 16px;
        }
        .gfp-detail-header {
          padding: 16px 20px; border-bottom: 1px solid var(--id-border);
          display: flex; align-items: center; justify-content: space-between;
          flex-wrap: wrap; gap: 12px;
        }
        .gfp-detail-title { font-weight: 700; font-size: 15px; color: var(--id-text); }
        .gfp-detail-preview { padding: 24px 20px; }
        .gfp-controls {
          display: grid; grid-template-columns: 1fr 1fr; gap: 12px;
          padding: 16px 20px; border-top: 1px solid var(--id-border);
          background: var(--id-surface-alt);
        }
        .gfp-size-row {
          display: flex; align-items: center; gap: 8px;
        }
        .gfp-size-val {
          font-size: 12px; font-weight: 600; min-width: 36px;
          text-align: right; color: var(--id-text-muted);
          font-family: 'JetBrains Mono', monospace;
        }
        .gfp-css {
          font-family: 'JetBrains Mono', monospace; font-size: 12px;
          background: var(--id-surface-alt); border: 1px solid var(--id-border);
          border-radius: 8px; padding: 14px; color: var(--id-text);
          white-space: pre-wrap; line-height: 1.6;
          width: 100%; box-sizing: border-box; resize: vertical; min-height: 120px;
        }
        .gfp-editable {
          width: 100%; border: none; background: transparent; color: inherit;
          font: inherit; resize: none; outline: none; padding: 0;
        }
        .gfp-editable:focus { outline: 1px dashed var(--id-border-strong); outline-offset: 4px; border-radius: 4px; }
        @media (max-width: 600px) {
          .gfp-grid { grid-template-columns: 1fr; }
          .gfp-controls { grid-template-columns: 1fr; }
        }
      `}</style>

      {/* Font pair cards */}
      <label className="mini-label">Font pairs</label>
      <div className="gfp-grid">
        {PAIRS.map((p, i) => (
          <div key={i}
               className={`gfp-card ${selected === i ? 'active' : ''}`}
               onClick={() => setSelected(i)}>
            <div className="gfp-card-heading"
                 style={{ fontFamily: `'${p.heading}', serif` }}>
              {p.heading}
            </div>
            <div className="gfp-card-body"
                 style={{ fontFamily: `'${p.body}', sans-serif` }}>
              A well-chosen pair of fonts creates visual hierarchy and harmony in your design.
            </div>
            <div className="gfp-card-meta">
              <span className="gfp-card-tag">{p.heading}</span>
              <span className="gfp-card-tag">{p.body}</span>
            </div>
          </div>
        ))}
      </div>

      {/* Detail view */}
      {pair && (
        <>
          <div className="gfp-detail">
            <div className="gfp-detail-header">
              <div className="gfp-detail-title">
                {pair.heading} + {pair.body}
              </div>
              {!fontsLoaded && (
                <span style={{ fontSize: 12, color: 'var(--id-text-muted)' }}>Loading fonts...</span>
              )}
            </div>

            <div className="gfp-detail-preview">
              <textarea className="gfp-editable" rows="2"
                        value={headingText}
                        onChange={(e) => setHeadingText(e.target.value)}
                        style={{
                          fontFamily: `'${pair.heading}', serif`,
                          fontSize: headingSize,
                          fontWeight: 700,
                          lineHeight: 1.2,
                          color: 'var(--id-text)',
                          marginBottom: 12,
                        }} />
              <textarea className="gfp-editable" rows="4"
                        value={bodyText}
                        onChange={(e) => setBodyText(e.target.value)}
                        style={{
                          fontFamily: `'${pair.body}', sans-serif`,
                          fontSize: bodySize,
                          fontWeight: 400,
                          lineHeight: 1.6,
                          color: 'var(--id-text-muted)',
                        }} />
            </div>

            <div className="gfp-controls">
              <div>
                <label className="mini-label">Heading size</label>
                <div className="gfp-size-row">
                  <input type="range" min="24" max="72" value={headingSize}
                         onChange={(e) => setHeadingSize(Number(e.target.value))}
                         className="cmp-slider" style={{ flex: 1 }} />
                  <span className="gfp-size-val">{headingSize}px</span>
                </div>
              </div>
              <div>
                <label className="mini-label">Body size</label>
                <div className="gfp-size-row">
                  <input type="range" min="14" max="24" value={bodySize}
                         onChange={(e) => setBodySize(Number(e.target.value))}
                         className="cmp-slider" style={{ flex: 1 }} />
                  <span className="gfp-size-val">{bodySize}px</span>
                </div>
              </div>
            </div>
          </div>

          {/* CSS output */}
          <label className="mini-label">CSS</label>
          <textarea className="gfp-css" readOnly value={getCSSOutput()}
                    onClick={(e) => e.target.select()} />

          <div className="cmp-actions">
            <button className="btn btn-secondary" onClick={() => setSelected(null)}>
              <window.Icon name="grid" size={16} /> All pairs
            </button>
            <button className="btn btn-primary" onClick={copyCSS}>
              <window.Icon name={copied ? 'check' : 'doc'} size={16} /> {copied ? 'Copied!' : 'Copy CSS'}
            </button>
          </div>
        </>
      )}
    </div>
  );
};
