// Sticker library — loads white-on-transparent SVGs from stickers/ folder,
// recolors via currentColor injection, supports user-uploaded files.

const { useState: useStLg, useEffect: useEfLg } = React;

// Auto-discovered stickers from stickers/ folder
const STICKER_FILES = [
  '01_badge_east_script', '02_badge_south_script', '03_badge_east_clean', '04_badge_south_clean',
  '05_badge_central_script', '06_badge_north_script', '07_badge_central_clean', '08_badge_north_clean',
  '09_pickup_script', '10_pickup_block', '11_wordmark_outline_large', '12_wordmark_solid_large',
  '13_sedan_script_1', '14_sedan_block_1', '15_wordmark_solid_small', '16_wordmark_outline_small',
  '17_script_panel_solid', '18_script_panel_outline', '19_sedan_script_2', '20_sedan_block_2',
  '21_south_outline', '22_south_solid', '23_circle_script', '24_suv_script', '25_suv_block',
  '26_north_outline', '27_north_solid', '28_east_outline', '29_east_solid', '30_circle_outline',
  '31_wagon_script', '32_wagon_block', '33_central_outline', '34_central_solid',
];

const STICKER_ASPECTS = {
  '01_badge_east_script': 1.063902,
  '02_badge_south_script': 1.058890,
  '03_badge_east_clean': 1.041006,
  '04_badge_south_clean': 1.041006,
  '05_badge_central_script': 1.056702,
  '06_badge_north_script': 1.059487,
  '07_badge_central_clean': 1.041013,
  '08_badge_north_clean': 1.041019,
  '09_pickup_script': 2.426865,
  '10_pickup_block': 2.299033,
  '11_wordmark_outline_large': 9.380392,
  '12_wordmark_solid_large': 9.735723,
  '13_sedan_script_1': 2.342895,
  '14_sedan_block_1': 2.371279,
  '15_wordmark_solid_small': 4.025630,
  '16_wordmark_outline_small': 3.969427,
  '17_script_panel_solid': 3.021361,
  '18_script_panel_outline': 2.993859,
  '19_sedan_script_2': 2.418656,
  '20_sedan_block_2': 2.375493,
  '21_south_outline': 2.930346,
  '22_south_solid': 2.925501,
  '23_circle_script': 1.183026,
  '24_suv_script': 2.173830,
  '25_suv_block': 2.271683,
  '26_north_outline': 2.985017,
  '27_north_solid': 2.925601,
  '28_east_outline': 2.984992,
  '29_east_solid': 2.874024,
  '30_circle_outline': 1.174484,
  '31_wagon_script': 2.081779,
  '32_wagon_block': 2.350089,
  '33_central_outline': 2.984992,
  '34_central_solid': 2.844900,
};

// Friendly labels
function prettifyName(slug) {
  // strip leading number, replace _
  const s = slug.replace(/^\d+_/, '').replace(/_/g, ' ');
  return s.replace(/\b\w/g, c => c.toUpperCase());
}

const BUILT_IN_STICKERS = STICKER_FILES.map(slug => ({
  id: 'st-' + slug,
  name: prettifyName(slug),
  type: 'sticker',
  src: 'stickers/' + slug + '.svg',
  aspect: STICKER_ASPECTS[slug] || 1,
}));

// Cache: sticker id → tinted SVG inner XML (with viewBox extracted)
const stickerCache = new Map();
// Cache: sticker id → { viewBox, raw }
const rawCache = new Map();

async function fetchSticker(src) {
  if (rawCache.has(src)) return rawCache.get(src);
  try {
    const res = await fetch(src);
    const text = await res.text();
    // Extract viewBox + inner content
    const vbMatch = text.match(/viewBox="([^"]+)"/);
    const viewBox = vbMatch ? vbMatch[1] : '0 0 200 200';
    // Extract content between <svg ...> and </svg>
    const innerMatch = text.match(/<svg[^>]*>([\s\S]*?)<\/svg>/);
    const inner = innerMatch ? innerMatch[1] : '';
    const data = { viewBox, inner };
    rawCache.set(src, data);
    return data;
  } catch (e) {
    return { viewBox: '0 0 200 200', inner: '<rect width="200" height="200" fill="currentColor" opacity="0.2"/>' };
  }
}

function tintSvgContent(inner) {
  // Replace explicit white fills with currentColor so CSS `color` controls tint
  return inner
    .replace(/fill="#ffffff"/gi, 'fill="currentColor"')
    .replace(/fill="#fff"/gi, 'fill="currentColor"')
    .replace(/fill="white"/gi, 'fill="currentColor"')
    .replace(/fill:\s*#ffffff/gi, 'fill:currentColor')
    .replace(/fill:\s*#fff(?![0-9a-f])/gi, 'fill:currentColor')
    .replace(/fill:\s*white/gi, 'fill:currentColor')
    .replace(/stroke="#ffffff"/gi, 'stroke="currentColor"')
    .replace(/stroke="#fff"/gi, 'stroke="currentColor"')
    .replace(/stroke:\s*#ffffff/gi, 'stroke:currentColor')
    .replace(/stroke:\s*#fff(?![0-9a-f])/gi, 'stroke:currentColor');
}

// React component: render an inline SVG sticker with currentColor tint
function Sticker({ src, color = 'currentColor', dataUri, viewBox: forcedVB, inlineMarkup }) {
  const [data, setData] = useStLg(null);

  useEfLg(() => {
    let cancelled = false;
    if (inlineMarkup) {
      // raw user-text or pre-tinted inline content
      setData({ viewBox: forcedVB || '0 0 200 200', inner: inlineMarkup, tinted: inlineMarkup });
      return;
    }
    if (dataUri) {
      // user-uploaded image → render as <image>
      setData({ dataUri: true });
      return;
    }
    fetchSticker(src).then(d => {
      if (cancelled) return;
      setData({ ...d, tinted: tintSvgContent(d.inner) });
    });
    return () => { cancelled = true; };
  }, [src, dataUri, inlineMarkup]);

  if (!data) {
    return <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet"><rect x="10" y="10" width="80" height="80" fill="currentColor" opacity="0.1"/></svg>;
  }
  if (data.dataUri) {
    return (
      <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
        <image href={dataUri} x="0" y="0" width="100" height="100" preserveAspectRatio="xMidYMid meet"/>
      </svg>
    );
  }
  return (
    <svg viewBox={data.viewBox} preserveAspectRatio="xMidYMid meet" style={{ color, overflow: 'visible' }}
         dangerouslySetInnerHTML={{ __html: data.tinted }}/>
  );
}

// Custom text rendered as SVG text
function StickerText({ text = 'TEXT', color = 'currentColor' }) {
  return (
    <svg viewBox="0 0 240 60" preserveAspectRatio="xMidYMid meet" style={{ color }}>
      <text x="120" y="44" textAnchor="middle"
            fontFamily="'Inter', sans-serif" fontWeight="800"
            fontSize="36" fill="currentColor" letterSpacing="2">{text || 'TEXT'}</text>
    </svg>
  );
}

// Renderer dispatcher used by editor + admin
function LogoRender({ logoId, color, customText, dataUri, customLib }) {
  if (logoId === 'user-text') return <StickerText text={customText} color={color}/>;
  if (logoId && logoId.startsWith('user-')) {
    // user-uploaded sticker — find in customLib
    const found = customLib && customLib.find(l => l.id === logoId);
    if (found && found.inlineMarkup) {
      return <Sticker inlineMarkup={found.inlineMarkup} viewBox={found.viewBox} color={color}/>;
    }
    if (found && found.dataUri) {
      return <Sticker dataUri={found.dataUri} color={color}/>;
    }
    return <StickerText text="?" color={color}/>;
  }
  if (logoId && logoId.startsWith('st-')) {
    const found = BUILT_IN_STICKERS.find(s => s.id === logoId);
    if (found) return <Sticker src={found.src} color={color}/>;
  }
  return <StickerText text="?" color={color}/>;
}

function aspectFromViewBox(viewBox) {
  const nums = String(viewBox || '').trim().split(/[ ,]+/).map(Number);
  return nums.length === 4 && nums[2] > 0 && nums[3] > 0 ? nums[2] / nums[3] : 1;
}

function getLogoAspectRatio(logoId, customText, customLib) {
  if (logoId === 'user-text') return 4;
  if (logoId && logoId.startsWith('user-')) {
    const found = customLib && customLib.find(l => l.id === logoId);
    return found?.aspect || aspectFromViewBox(found?.viewBox) || 1;
  }
  const found = BUILT_IN_STICKERS.find(s => s.id === logoId);
  return found?.aspect || 1;
}

Object.assign(window, {
  BUILT_IN_STICKERS, Sticker, StickerText, LogoRender, fetchSticker, tintSvgContent,
  getLogoAspectRatio, aspectFromViewBox,
});
