// ShareLinks.jsx — share controls for a blog post. The share target is the
// post's canonical skardi.ai URL rather than window.location, so a link shared
// from localhost or from a PR preview environment still points at production.
const SHARE_ICONS = {
  x: <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />,
  linkedin: <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 1 1 0-4.125 2.062 2.062 0 0 1 0 4.125zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.454C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.225 0z" />,
};

// Clipboard API needs a secure context; fall back for plain-http origins.
const copyText = async (text) => {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text);
      return true;
    }
  } catch (e) { /* fall through to the textarea path */ }
  try {
    const ta = document.createElement('textarea');
    ta.value = text;
    ta.setAttribute('readonly', '');
    ta.style.cssText = 'position:fixed;top:-9999px;opacity:0';
    document.body.appendChild(ta);
    ta.select();
    const ok = document.execCommand('copy');
    document.body.removeChild(ta);
    return ok;
  } catch (e) {
    return false;
  }
};

const ShareLinks = ({ url, title }) => {
  const [copied, setCopied] = React.useState(false);
  const [failed, setFailed] = React.useState(false);

  // Both outcomes are transient: a stuck "Copy failed" would outlive the
  // problem and leave the button looking broken for the rest of the visit.
  React.useEffect(() => {
    if (!copied && !failed) return;
    const t = setTimeout(() => { setCopied(false); setFailed(false); }, 2000);
    return () => clearTimeout(t);
  }, [copied, failed]);

  const onCopy = async () => {
    const ok = await copyText(url);
    setCopied(ok);
    setFailed(!ok);
    if (ok) window.skardiTrack?.('post_shared', { network: 'copy_link', url });
  };

  const targets = [
    {
      id: 'x',
      label: 'Share on X',
      href: `https://x.com/intent/post?url=${encodeURIComponent(url)}&text=${encodeURIComponent(title)}`,
    },
    {
      id: 'linkedin',
      label: 'Share on LinkedIn',
      href: `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`,
    },
  ];

  const control = {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    gap: 8, height: 34, padding: '0 12px',
    borderRadius: 8, cursor: 'pointer',
    background: 'rgba(125,211,252,0.05)',
    border: '1px solid rgba(125,211,252,0.12)',
    color: '#8ea3c0', textDecoration: 'none',
    fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
    letterSpacing: '0.04em',
    transition: 'color 150ms, border-color 150ms, background 150ms',
  };
  const hoverOn = (e) => {
    e.currentTarget.style.color = '#2ee89a';
    e.currentTarget.style.borderColor = 'rgba(46,232,154,0.35)';
    e.currentTarget.style.background = 'rgba(46,232,154,0.07)';
  };
  const hoverOff = (e) => {
    e.currentTarget.style.color = '#8ea3c0';
    e.currentTarget.style.borderColor = 'rgba(125,211,252,0.12)';
    e.currentTarget.style.background = 'rgba(125,211,252,0.05)';
  };

  return (
    <div className="post-share" style={{
      display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap',
    }}>
      <span style={{
        fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
        letterSpacing: '0.12em', textTransform: 'uppercase', color: '#6b7e9a',
      }}>Share</span>

      {targets.map((t) => (
        <a key={t.id} href={t.href} target="_blank" rel="noopener noreferrer"
          aria-label={t.label} title={t.label}
          onClick={() => window.skardiTrack?.('post_shared', { network: t.id, url })}
          style={{ ...control, width: 34, padding: 0 }}
          onMouseEnter={hoverOn} onMouseLeave={hoverOff}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
            {SHARE_ICONS[t.id]}
          </svg>
        </a>
      ))}

      <button type="button" onClick={onCopy}
        aria-label="Copy link to this post" title="Copy link to this post"
        style={{ ...control, color: copied ? '#2ee89a' : control.color }}
        onMouseEnter={hoverOn}
        onMouseLeave={(e) => { if (!copied) hoverOff(e); }}>
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
          aria-hidden="true">
          {copied
            ? <polyline points="20 6 9 17 4 12" />
            : <><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" /><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" /></>}
        </svg>
        {copied ? 'Copied' : failed ? 'Copy failed' : 'Copy link'}
      </button>

      {/* Announce the result to screen readers, which get nothing from a colour change. */}
      <span role="status" aria-live="polite" style={{
        position: 'absolute', width: 1, height: 1, overflow: 'hidden',
        clip: 'rect(0 0 0 0)', whiteSpace: 'nowrap',
      }}>{copied ? 'Link copied to clipboard' : ''}</span>
    </div>
  );
};

window.ShareLinks = ShareLinks;
