import React, { useMemo } from 'react';
import { usePublicSettings } from '../../hooks/usePublicSettings';

// Normalizes various social URL formats to a proper https URL
const normalizeSocialUrl = (network: 'facebook' | 'instagram' | 'youtube', raw?: string | null): string | null => {
  let v = String(raw || '').trim();
  if (!v) return null;
  // Replace whitespace
  v = v.replace(/\s+/g, '');
  // Accept handle like @club
  if (v.startsWith('@')) {
    const handle = v.slice(1);
    if (network === 'facebook') return `https://www.facebook.com/${handle}`;
    if (network === 'instagram') return `https://www.instagram.com/${handle}`;
    if (network === 'youtube') return `https://www.youtube.com/@${handle}`;
  }
  // If only a username without slashes
  if (!/^https?:\/\//i.test(v) && !v.includes('/') && !v.includes('.')) {
    if (network === 'facebook') return `https://www.facebook.com/${v}`;
    if (network === 'instagram') return `https://www.instagram.com/${v}`;
    if (network === 'youtube') return `https://www.youtube.com/@${v}`;
  }
  // If looks like domain without scheme
  if (!/^https?:\/\//i.test(v)) {
    if (/^facebook\.com\//i.test(v)) return `https://www.${v}`;
    if (/^instagram\.com\//i.test(v)) return `https://www.${v}`;
    if (/^youtube\.com\//i.test(v)) return `https://www.${v}`;
  }
  return v;
};

const SocialEmbeds: React.FC<{ variant?: 'unified' | 'magazine' | 'pro' | 'edge' }>
  = ({ variant = 'unified' }) => {
  const { data: settings } = usePublicSettings();

  const facebookHref = useMemo(() => {
    const raw = (settings as any)?.facebook_url
      || (settings as any)?.facebook
      || (settings as any)?.facebookPage
      || (settings as any)?.facebook_page
      || (settings as any)?.facebookPageUrl
      || (settings as any)?.facebook_page_url;
    return normalizeSocialUrl('facebook', raw);
  }, [settings]);

  const instagramHref = useMemo(() => {
    const raw = (settings as any)?.instagram_url
      || (settings as any)?.instagram
      || (settings as any)?.instagramProfile
      || (settings as any)?.instagram_profile
      || (settings as any)?.ig
      || (settings as any)?.ig_url;
    return normalizeSocialUrl('instagram', raw);
  }, [settings]);

  const youtubeHref = useMemo(() => {
    const raw = (settings as any)?.youtube_url
      || (settings as any)?.youtube
      || (settings as any)?.yt
      || (settings as any)?.youtube_channel;
    return normalizeSocialUrl('youtube', raw);
  }, [settings]);

  if (!instagramHref && !youtubeHref) return null;

  const outerStyle: React.CSSProperties = {
    margin: variant === 'pro' ? '16px 0' : '8px 0',
  };
  const gridStyle: React.CSSProperties = {
    display: 'grid',
    gridTemplateColumns: '1fr',
    gap: 12,
  };
  const colStyle: React.CSSProperties = {
    background: '#fff',
    borderRadius: 10,
    border: '1px solid var(--light-gray)',
    padding: 8,
  };

  // Instagram profile embed is unofficial; try /embed fallback, else show CTA tile
  const instagramEmbedSrc = instagramHref ? `${instagramHref.replace(/\/$/, '')}/embed` : null;

  return (
    <div className={`social-embeds ${variant}`} style={outerStyle}>
      <div className="section-head" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 8 }}>
        <h3 style={{ margin: 0 }}>Sledujte nás</h3>
        <div className="links" style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {facebookHref && (<a className="btn" href={facebookHref} target="_blank" rel="noreferrer noopener">Facebook</a>)}
          {instagramHref && (<a className="btn" href={instagramHref} target="_blank" rel="noreferrer noopener">Instagram</a>)}
          {youtubeHref && (<a className="btn" href={youtubeHref} target="_blank" rel="noreferrer noopener">YouTube</a>)}
        </div>
      </div>

      <div className="grid" style={gridStyle}>
        {instagramHref && (
          <div className="col" style={colStyle}>
            {instagramEmbedSrc ? (
              <iframe
                title="Instagram"
                src={instagramEmbedSrc}
                width="100%"
                height={360}
                style={{ border: 0, width: '100%' }}
                frameBorder={0}
                scrolling="no"
              />
            ) : (
              <div style={{ padding: 16 }}>
                <p>Sledujte nás na Instagramu.</p>
                <a className="btn" href={instagramHref} target="_blank" rel="noreferrer noopener">Otevřít Instagram</a>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default SocialEmbeds;
