// blocks.jsx — email content renderers + selectable block shell

const SOCIAL_SVGS = {
  facebook: (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
      <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"/>
    </svg>
  ),
  instagram: (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" xmlns="http://www.w3.org/2000/svg">
      <rect x="2" y="2" width="20" height="20" rx="5" ry="5"/>
      <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/>
      <line x1="17.5" y1="6.5" x2="17.51" y2="6.5" strokeWidth="2.5"/>
    </svg>
  ),
  whatsapp: (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413z"/>
    </svg>
  ),
  linkedin: (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
      <path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"/>
      <rect x="2" y="9" width="4" height="12"/>
      <circle cx="4" cy="4" r="2"/>
    </svg>
  ),
};

function socialUrl(key, value) {
  if (!value || !value.trim()) return null;
  const v = value.trim();
  if (v.startsWith('http')) return v;
  if (key === 'facebook')  return 'https://facebook.com/' + v;
  if (key === 'instagram') return 'https://instagram.com/' + v;
  if (key === 'whatsapp')  return 'https://wa.me/' + v;
  if (key === 'linkedin')  return 'https://linkedin.com/in/' + v;
  return v;
}

const TYPE_META = {
  header: { label: "Header", settings: "Header settings" },
  offer:  { label: "Offer",  settings: "Offer settings" },
  cruise: { label: "Cruise", settings: "Cruise settings" },
  text:   { label: "Text",   settings: "Text settings" },
  image:  { label: "Image",  settings: "Image settings" },
  video:  { label: "Video",  settings: "Video settings" },
  footer: { label: "Footer", settings: "Footer settings" },
};

// ---- individual renderers (read from block.props) ----
function HeaderBlock({ p }) {
  const { Phone } = window.Icons;
  const bg = p.bgColor || '#0A6E6E';
  const fg = p.textColor || '#ffffff';
  const socials = p.socials || {};
  const socialLinks = ['facebook', 'instagram', 'whatsapp', 'linkedin']
    .map(k => ({ key: k, url: socialUrl(k, socials[k]) }))
    .filter(e => e.url);
  return (
    <div className="em-header" style={{ background: bg, color: fg }}>
      {(p.logoUrl && p.logoUrl.trim())
        ? <img src={p.logoUrl} alt={p.logoText || 'Logo'} style={{ maxHeight: 60, width: 'auto', display: 'block', margin: '0 auto 8px' }} />
        : <div className="em-header-mark"><h1 style={{ color: fg }}>{p.logoText || p.brand || 'Brand name'}</h1></div>
      }
      {p.tagline ? <p style={{ color: fg }}>{p.tagline}</p> : null}
      {p.phone ? (
        <p className="em-header-phone" style={{ color: fg }}>
          <Phone sw={1.5} />{p.phone}
        </p>
      ) : null}
      {socialLinks.length > 0 && (
        <div className="em-header-socials">
          {socialLinks.map(({ key, url }) => (
            <a key={key} href={url} className="em-header-social-link" style={{ color: fg }} target="_blank" rel="noopener noreferrer">
              {SOCIAL_SVGS[key]}
            </a>
          ))}
        </div>
      )}
    </div>
  );
}

function OfferBlock({ p }) {
  const { Tag, Shield } = window.Icons;
  const hasImg = p.imageUrl && p.imageUrl.trim();
  return (
    <div className="em-offer">
      <div className="em-offer-card">
        <div className={"em-offer-img" + (hasImg ? "" : " is-empty")}
             style={hasImg ? { backgroundImage: `url("${p.imageUrl}")` } : null}>
          {p.badge ? <span className="em-offer-badge">{p.badge}</span> : null}
          {!hasImg && (
            <span className="em-offer-img-placeholder"><Tag sw={1.6} />Holiday image</span>
          )}
        </div>
        <div className="em-offer-body">
          <div className="em-offer-top">
            <h2 className="em-offer-dest">{p.destination || "Destination"}</h2>
            {p.price ? <span className="em-offer-price">{p.price}</span> : null}
          </div>
          {p.headline ? <p className="em-offer-headline">{p.headline}</p> : null}
          {p.availability ? (
            <span className="em-offer-avail"><Shield />{p.availability}</span>
          ) : null}
          <a className="em-offer-cta" href={p.ctaUrl || '#'} style={{ background: p.buttonColor || "var(--tms-teal-500)" }}>
            {p.buttonText || "View this offer"}
          </a>
          {p.operator ? <p className="em-operated-by">Operated by {p.operator}</p> : null}
        </div>
      </div>
    </div>
  );
}

function CruiseBlock({ p }) {
  const { Cruise } = window.Icons;
  const hasImg = p.imageUrl && p.imageUrl.trim();
  const detailParts = [
    p.departureDate,
    p.duration && `${p.duration} nights`,
    p.departurePort,
    p.regions,
  ].filter(Boolean);
  return (
    <div className="em-offer">
      <div className="em-offer-card">
        <div className={"em-offer-img" + (hasImg ? "" : " is-empty")}
             style={hasImg ? { backgroundImage: `url("${p.imageUrl}")` } : null}>
          {p.promoBadge ? (
            <span className="em-offer-badge" style={{ background: '#F5A623' }}>{p.promoBadge}</span>
          ) : null}
          {!hasImg && (
            <span className="em-offer-img-placeholder"><Cruise sw={1.6} />Cruise image</span>
          )}
        </div>
        <div className="em-offer-body">
          <div className="em-offer-top">
            <h2 className="em-offer-dest">{p.cruiseName || "Cruise name"}</h2>
            {p.price ? <span className="em-offer-price">{p.price}</span> : null}
          </div>
          {p.operatorLine ? <p className="em-offer-headline" style={{ color: 'var(--product-fg-muted)', marginTop: 4, marginBottom: 2, fontSize: 13 }}>{p.operatorLine}</p> : null}
          {detailParts.length > 0 ? <p className="em-offer-headline">{detailParts.join(' · ')}</p> : null}
          {p.teaser ? <p className="em-offer-headline" style={{ fontStyle: 'italic' }}>{p.teaser}</p> : null}
          <a className="em-offer-cta" href={p.ctaUrl || '#'} style={{ background: p.ctaColor || '#0A6E7E' }}>
            View cruise
          </a>
          {p.operatorLine ? <p className="em-operated-by">Operated by {p.operatorLine.split('·')[0].trim()}</p> : null}
        </div>
      </div>
    </div>
  );
}

const _fmtBtnStyle = {
  background: 'none', border: 'none', color: '#ffffff',
  width: '28px', height: '28px', borderRadius: '4px',
  cursor: 'pointer', fontSize: '13px', fontWeight: '600',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
};

function FormatToolbar({ position, onFormat, onLinkModeChange }) {
  const [linkMode, setLinkMode] = React.useState(false);
  const [linkUrl, setLinkUrl] = React.useState('https://');
  const inputRef = React.useRef(null);

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

  if (!position) return null;

  const enterLink = () => { setLinkMode(true); onLinkModeChange && onLinkModeChange(true); };
  const exitLink  = () => { setLinkMode(false); setLinkUrl('https://'); onLinkModeChange && onLinkModeChange(false); };
  const applyLink = () => { onFormat('link', linkUrl); exitLink(); };

  const toolbarStyle = {
    position: 'fixed',
    top: position.top - 44,
    left: position.left,
    zIndex: 1000,
    background: '#1a1918',
    borderRadius: '6px',
    padding: '4px 6px',
    display: 'flex',
    alignItems: 'center',
    gap: '4px',
    boxShadow: '0 2px 8px rgba(0,0,0,0.35)',
    transform: 'translateX(-50%)',
  };

  if (linkMode) {
    return (
      <div style={toolbarStyle}>
        <input
          ref={inputRef}
          value={linkUrl}
          onChange={e => setLinkUrl(e.target.value)}
          onMouseDown={e => e.stopPropagation()}
          onKeyDown={e => {
            if (e.key === 'Enter')  { applyLink(); }
            if (e.key === 'Escape') { exitLink(); }
          }}
          placeholder="https://"
          style={{
            background: '#2c2c2a', border: '1px solid #4a4a48', borderRadius: '4px',
            color: '#ffffff', padding: '3px 8px', fontSize: '12px',
            width: '200px', outline: 'none', fontFamily: 'inherit',
          }}
        />
        <button onMouseDown={e => e.preventDefault()} onClick={applyLink}
                style={{ ..._fmtBtnStyle, color: '#4ade80', fontSize: '14px' }} title="Apply link">{'✓'}</button>
        <button onMouseDown={e => e.preventDefault()} onClick={exitLink}
                style={{ ..._fmtBtnStyle, color: '#f87171', fontSize: '14px' }} title="Cancel">{'✕'}</button>
      </div>
    );
  }

  return (
    <div style={toolbarStyle}>
      <button onMouseDown={e => e.preventDefault()} onClick={() => onFormat('bold')}               style={_fmtBtnStyle} title="Bold"><b>B</b></button>
      <button onMouseDown={e => e.preventDefault()} onClick={() => onFormat('italic')}             style={_fmtBtnStyle} title="Italic"><i>I</i></button>
      <button onMouseDown={e => e.preventDefault()} onClick={() => onFormat('insertUnorderedList')} style={_fmtBtnStyle} title="Bullets">{'•≡'}</button>
      <button onMouseDown={e => e.preventDefault()} onClick={enterLink}                            style={_fmtBtnStyle} title="Insert link">{'🔗'}</button>
    </div>
  );
}

function TextBlock({ p, onChange }) {
  const ref = React.useRef(null);
  const [toolbarPos, setToolbarPos] = React.useState(null);
  const linkActiveRef = React.useRef(false);

  React.useLayoutEffect(() => {
    if (ref.current) ref.current.innerHTML = p.html || '';
  }, []);

  React.useEffect(() => {
    const el = ref.current;
    if (el && document.activeElement !== el) el.innerHTML = p.html || '';
  }, [p.html]);

  const handleSelect = () => {
    const sel = window.getSelection();
    if (!sel || sel.isCollapsed) { setToolbarPos(null); return; }
    const rect = sel.getRangeAt(0).getBoundingClientRect();
    if (rect.width === 0) { setToolbarPos(null); return; }
    setToolbarPos({ top: rect.top, left: rect.left + rect.width / 2 });
  };

  const handleFormat = (command, value = null) => {
    if (command === 'link') {
      if (value) document.execCommand('createLink', false, value);
    } else {
      document.execCommand(command, false, null);
    }
    if (ref.current && onChange) onChange('html', ref.current.innerHTML);
    setToolbarPos(null);
  };

  return (
    <div className="em-text">
      <div
        ref={ref}
        contentEditable
        suppressContentEditableWarning
        onMouseUp={handleSelect}
        onKeyUp={handleSelect}
        onMouseDown={(e) => e.stopPropagation()}
        onClick={(e) => e.stopPropagation()}
        onBlur={() => setTimeout(() => { if (!linkActiveRef.current) setToolbarPos(null); }, 150)}
        onInput={(e) => onChange && onChange('html', e.currentTarget.innerHTML)}
        style={{ outline: 'none', minHeight: '3em', cursor: 'text' }}
      />
      {toolbarPos && ReactDOM.createPortal(
        <FormatToolbar position={toolbarPos} onFormat={handleFormat}
                       onLinkModeChange={(active) => { linkActiveRef.current = active; }} />,
        document.body
      )}
    </div>
  );
}

function ImageBlock({ p }) {
  const Image = window.Icons.Image;
  const hasImg = p.imageUrl && p.imageUrl.trim();
  return (
    <div className="em-image">
      <div className={"em-image-inner" + (hasImg ? "" : " is-empty")}
           style={hasImg ? { backgroundImage: `url("${p.imageUrl}")` } : null}>
        {!hasImg && <span className="em-image-ph"><Image sw={1.6} />Image — set a URL</span>}
      </div>
    </div>
  );
}

function VideoBlock({ p }) {
  const Video = window.Icons.Video;
  const hasImg = p.thumbUrl && p.thumbUrl.trim();
  return (
    <div className="em-video">
      <div className="em-video-inner" style={hasImg ? { backgroundImage: `url("${p.thumbUrl}")` } : null}>
        <span className="em-video-play"><Video sw={0} fill="currentColor" /></span>
        {p.title ? <span className="em-video-title">{p.title}</span> : null}
      </div>
    </div>
  );
}

function FooterBlock({ p }) {
  const bg = p.bgColor || '#F0F1F4';
  const fg = p.textColor || '#4D4A44';
  return (
    <div className="em-footer" style={{ background: bg }}>
      <b style={{ color: fg }}>{p.company || "Company name"}</b>
      {p.address ? <p style={{ color: fg }}>{p.address}</p> : null}
      <div className="em-footer-links" style={{ color: fg }}>
        <a style={{ color: fg }}>Unsubscribe</a><span>·</span><a style={{ color: fg }}>View in browser</a><span>·</span><a style={{ color: fg }}>Privacy</a>
      </div>
    </div>
  );
}

const RENDERERS = {
  header: HeaderBlock, offer: OfferBlock, cruise: CruiseBlock, text: TextBlock,
  image: ImageBlock, video: VideoBlock, footer: FooterBlock,
};

// ---- selectable shell with action rail ----
function BlockShell({ block, index, total, selected, onSelect, onMove, onDup, onDelete, onChange }) {
  const R = RENDERERS[block.type];
  const { ArrowUp, ArrowDown, Copy, Trash } = window.Icons;
  return (
    <div className="bld-block-wrap">
      <div className={"bld-block" + (selected ? " is-selected" : "")}
           onClick={(e) => { e.stopPropagation(); onSelect(block.id); }}>
        {selected && <span className="bld-block-tag">{TYPE_META[block.type].label}</span>}
        <R p={block.props} onChange={onChange ? (key, val) => onChange(block.id, key, val) : undefined} />
        {selected && (
          <div className="bld-actions" onClick={(e) => e.stopPropagation()}>
            <button className="bld-action" title="Move up" disabled={index === 0}
                    onClick={() => onMove(block.id, -1)}><ArrowUp /></button>
            <button className="bld-action" title="Move down" disabled={index === total - 1}
                    onClick={() => onMove(block.id, 1)}><ArrowDown /></button>
            <button className="bld-action" title="Duplicate" onClick={() => onDup(block.id)}><Copy /></button>
            <button className="bld-action is-danger" title="Delete" onClick={() => onDelete(block.id)}><Trash /></button>
          </div>
        )}
      </div>
    </div>
  );
}

window.TYPE_META = TYPE_META;
window.BlockShell = BlockShell;
