// 52 tools across 4 categories (pdf, image, converter, file).
// `working: true` flips the "Live demo" pill on the card; it's a presentational flag.
// The actual tool UI comes from tools/<id>.jsx via window.TOOL_HANDLERS.

window.TOOLS = [
  // PDF (14) — all coming soon, need a PDF library
  { id: 'merge-pdf',    name: 'Merge PDF',     cat: 'pdf', desc: 'Combine multiple PDFs into one file', featured: true, icon: 'merge', working: true },
  { id: 'split-pdf',    name: 'Split PDF',     cat: 'pdf', desc: 'Separate one PDF into multiple files', icon: 'split', working: true },
  { id: 'compress-pdf', name: 'Compress PDF',  cat: 'pdf', desc: 'Lessen the file size of a PDF file', icon: 'minify', working: true },
  { id: 'pdf-to-word',  name: 'PDF to Word',   cat: 'pdf', desc: 'Convert PDF to editable DOCX', featured: true, icon: 'doc', working: true },
  { id: 'word-to-pdf',  name: 'Word to PDF',   cat: 'pdf', desc: 'Turn DOCX files into PDF', icon: 'doc', working: true },
  { id: 'pdf-to-jpg',   name: 'PDF to JPG',    cat: 'pdf', desc: 'Convert each PDF page into an image', icon: 'image', working: true },
  { id: 'jpg-to-pdf',   name: 'JPG to PDF',    cat: 'pdf', desc: 'Upload images and receive a PDF', icon: 'doc', working: true },
  { id: 'edit-pdf',     name: 'Edit PDF',      cat: 'pdf', desc: 'Free online PDF editor', icon: 'edit', working: true, fullscreen: true },
  { id: 'rotate-pdf',   name: 'Rotate PDF',    cat: 'pdf', desc: 'Rotate pages as you need them', icon: 'rotate', working: true },
  { id: 'pdf-to-excel', name: 'PDF to Excel',  cat: 'pdf', desc: 'Extract tables from PDF into spreadsheets', icon: 'table', working: true },
  { id: 'ocr-pdf',      name: 'OCR PDF',       cat: 'pdf', desc: 'Make scanned PDFs searchable', icon: 'scan', working: true },
  { id: 'scanned-pdf',  name: 'Scanned PDF',   cat: 'pdf', desc: 'Convert a PDF to look like a scanned document', icon: 'scan', working: true },

  // Image (16)
  { id: 'compress-image',  name: 'Compress Image',    cat: 'image', desc: 'Lessen the file size of an image', featured: true, icon: 'minify', working: true },
  { id: 'remove-bg',       name: 'Remove Background', cat: 'image', desc: 'Easily remove the background from a photo', featured: true, icon: 'bg', working: true },
  { id: 'resize-image',    name: 'Resize Image',      cat: 'image', desc: 'Change the dimensions of your image', icon: 'resize', working: true },
  { id: 'crop-image',      name: 'Crop Image',        cat: 'image', desc: 'Trim photos to the perfect frame', icon: 'crop', working: true },
  { id: 'upscale-image',   name: 'Upscale Image',     cat: 'image', desc: 'Increase the resolution of your image', icon: 'upscale', working: true },
  { id: 'image-to-text',   name: 'Image to Text',     cat: 'image', desc: 'Extract text from pictures with OCR', icon: 'scan', working: true },
  { id: 'blur-background', name: 'Blur Background',   cat: 'image', desc: 'Apply a soft blur to photo backgrounds', icon: 'blur', working: true },
  { id: 'rotate-image',    name: 'Rotate Image',      cat: 'image', desc: 'Flip or rotate photos quickly', icon: 'rotate', working: true },
  { id: 'meme-generator',  name: 'Meme Generator',    cat: 'image', desc: 'Make memes from any picture', icon: 'smile', working: true },
  { id: 'color-picker',    name: 'Color Picker',      cat: 'image', desc: 'Grab exact colors from any image', icon: 'droplet', working: true },
  { id: 'photo-filter',    name: 'Photo Filter',      cat: 'image', desc: 'Apply stylish filters to your photos', icon: 'filter', working: true },
  { id: 'convert-webp',    name: 'Image to WebP',     cat: 'image', desc: 'Convert any image to WebP format', icon: 'image', working: true },
  { id: 'pixelate',        name: 'Pixelate Image',    cat: 'image', desc: 'Pixelate parts of a photo', icon: 'pixel', working: true },
  { id: 'collage',         name: 'Photo Collage',     cat: 'image', desc: 'Make a collage from multiple photos', icon: 'grid', working: true },
  { id: 'color-shades',    name: 'Color Shades',      cat: 'image', desc: 'Generate all tints and shades of a color', icon: 'droplet', working: true },
  { id: 'color-extractor', name: 'Color Extractor',   cat: 'image', desc: 'Extract a full color palette from any image', icon: 'palette', working: true },
  { id: 'color-mixer',     name: 'Color Mixer',       cat: 'image', desc: 'Blend two colors and see intermediate steps', icon: 'droplet', working: true },
  { id: 'svg-blob',        name: 'SVG Blob Generator',cat: 'image', desc: 'Create random organic SVG blob shapes', icon: 'sparkle', working: true },
  { id: 'svg-pattern',     name: 'SVG Pattern',       cat: 'image', desc: 'Generate repeating SVG background patterns', icon: 'grid', working: true },
  { id: 'instagram-post',  name: 'Instagram Post',    cat: 'image', desc: 'Create realistic Instagram post mockups', icon: 'image', working: true },
  { id: 'photo-finder',    name: 'Face Recognition', cat: 'image', desc: 'Find yourself across gallery photos using face recognition', featured: true, icon: 'scan', working: true },

  // Converter (12)
  { id: 'heic-to-jpg', name: 'HEIC to JPG',      cat: 'converter', desc: 'Convert iPhone HEIC files to JPG', featured: true, icon: 'swap', working: true },
  { id: 'heic-to-png', name: 'HEIC to PNG',      cat: 'converter', desc: 'Convert HEIC images to PNG', icon: 'swap', working: true },
  { id: 'png-to-jpg',  name: 'PNG to JPG',       cat: 'converter', desc: 'Convert PNGs to JPG format', icon: 'swap', working: true },
  { id: 'jpg-to-png',  name: 'JPG to PNG',       cat: 'converter', desc: 'Convert JPG files to transparent PNGs', icon: 'swap', working: true },
  { id: 'webp-to-jpg', name: 'WebP to JPG',      cat: 'converter', desc: 'Turn WebP images into JPGs', icon: 'swap', working: true },
  { id: 'svg-to-png',  name: 'SVG to PNG',       cat: 'converter', desc: 'Rasterize SVGs into PNGs', icon: 'swap', working: true },
  { id: 'csv-to-excel',name: 'CSV to Excel',     cat: 'converter', desc: 'Turn CSV files into XLSX', icon: 'table', working: true },
  { id: 'xml-to-json', name: 'XML to JSON',      cat: 'converter', desc: 'Convert XML structures to JSON', icon: 'code', working: true },
  { id: 'md-to-html',  name: 'Markdown to HTML', cat: 'converter', desc: 'Render Markdown to clean HTML', icon: 'code', working: true },
  { id: 'html-to-pdf', name: 'HTML to PDF',      cat: 'converter', desc: 'Save any web page as a PDF', icon: 'doc', working: true },
  { id: 'json-yaml',  name: 'JSON ↔ YAML',     cat: 'converter', desc: 'Convert between JSON and YAML formats', icon: 'swap', working: true },
  { id: 'json-formatter', name: 'JSON Formatter', cat: 'converter', desc: 'Format, validate and explore JSON data', icon: 'code', working: true },
  { id: 'base64-codec',    name: 'Base64 Encode/Decode', cat: 'converter', desc: 'Encode text to Base64 or decode back', icon: 'code', working: true },
  { id: 'url-codec',       name: 'URL Encode/Decode',    cat: 'converter', desc: 'Encode or decode URL components', icon: 'code', working: true },
  { id: 'html-codec',      name: 'HTML Encode/Decode',   cat: 'converter', desc: 'Escape or unescape HTML entities', icon: 'code', working: true },
  { id: 'image-to-base64', name: 'Image to Base64',      cat: 'converter', desc: 'Convert images to Base64 data strings', icon: 'code', working: true },
  { id: 'jwt-codec',       name: 'JWT Decoder',          cat: 'converter', desc: 'Decode, inspect and debug JWT tokens', icon: 'lock', working: true },
  { id: 'hex-rgba',        name: 'HEX ↔ RGBA',           cat: 'converter', desc: 'Convert between HEX and RGBA color formats', icon: 'droplet', working: true },

  // File (10)
  { id: 'compress-file', name: 'Compress File',       cat: 'file', desc: 'Shrink files without losing quality', icon: 'minify', working: true },
  { id: 'split-excel',   name: 'Split Excel',         cat: 'file', desc: 'Split a workbook by sheet', featured: true, icon: 'split', working: true },
  { id: 'merge-excel',   name: 'Merge Excel',         cat: 'file', desc: 'Combine spreadsheets into one', icon: 'merge', working: true },
  { id: 'zip-files',     name: 'Zip Files',           cat: 'file', desc: 'Pack multiple files into a .zip', icon: 'archive', working: true },
  { id: 'unzip',         name: 'Unzip File',          cat: 'file', desc: 'Extract files from a .zip archive', icon: 'archive', working: true },
  { id: 'rename-batch',  name: 'Batch Rename',        cat: 'file', desc: 'Rename many files at once', icon: 'edit', working: true },
  { id: 'file-hash',     name: 'File Hash',           cat: 'file', desc: 'Get MD5/SHA hashes for any file', icon: 'lock', working: true },
  { id: 'qr-generator',  name: 'QR Code Generator',   cat: 'file', desc: 'Make QR codes for links and text', icon: 'qr', working: true },
  { id: 'password-gen',  name: 'Password Generator',  cat: 'file', desc: 'Generate strong random passwords', icon: 'lock', working: true },
  { id: 'word-counter',  name: 'Word Counter',        cat: 'file', desc: 'Count words and characters fast', icon: 'text', working: true },
  { id: 'diff-viewer',   name: 'Diff Viewer',         cat: 'file', desc: 'Compare two texts and see changes line by line', icon: 'code', working: true },
  { id: 'epub-reader',   name: 'EPUB Reader',         cat: 'file', desc: 'Read EPUB books right in your browser', icon: 'doc', working: true },
  { id: 'barcode-generator', name: 'Barcode Generator', cat: 'file', desc: 'Create CODE128, EAN and UPC barcodes', icon: 'barcode', working: true },

  // Text (4) — text manipulation & generation
  { id: 'case-converter',      name: 'Case Converter',        cat: 'text', desc: 'Convert text to upper, lower, title, camel or snake case', featured: true, icon: 'text', working: true },
  { id: 'lorem-ipsum',         name: 'Lorem Ipsum Generator', cat: 'text', desc: 'Generate placeholder text with custom paragraphs', icon: 'doc', working: true },
  { id: 'text-to-handwriting', name: 'Text to Handwriting',   cat: 'text', desc: 'Turn typed text into realistic handwriting on paper', featured: true, icon: 'pen', working: true },
  { id: 'bionic-reading',      name: 'Bionic Reading',        cat: 'text', desc: 'Bold the first half of each word for faster reading', icon: 'bolt', working: true },

  // Developer (8) — CSS generators & code utilities
  { id: 'css-gradient',      name: 'CSS Gradient',       cat: 'developer', desc: 'Design beautiful CSS gradients with live preview', featured: true, icon: 'palette', working: true },
  { id: 'css-box-shadow',    name: 'CSS Box Shadow',     cat: 'developer', desc: 'Generate CSS box-shadow with visual controls', icon: 'shadow', working: true },
  { id: 'css-glassmorphism', name: 'Glassmorphism',      cat: 'developer', desc: 'Create frosted-glass CSS effects', icon: 'layers', working: true },
  { id: 'css-clip-path',     name: 'CSS Clip Path',      cat: 'developer', desc: 'Shape elements with interactive clip-path editor', icon: 'crop', working: true },
  { id: 'css-cubic-bezier',  name: 'Cubic Bezier',       cat: 'developer', desc: 'Design animation easing curves visually', icon: 'bezier', working: true },
  { id: 'css-loader',        name: 'CSS Loader',         cat: 'developer', desc: 'Pick and customize animated loading spinners', icon: 'rotate', working: true },
  { id: 'code-to-image',     name: 'Code to Image',      cat: 'developer', desc: 'Turn code snippets into beautiful shareable images', featured: true, icon: 'code', working: true },
  { id: 'google-fonts-pair', name: 'Font Pair Finder',   cat: 'developer', desc: 'Find Google Font combinations that look great together', icon: 'type', working: true },

  // Sports (18) — runner-focused calculators, GPS file tools, race-day helpers.
  // The 'group' field powers sub-sections on the dedicated /sports page.
  { id: 'pace-calculator',     name: 'Pace Calculator',      cat: 'sports', group: 'calculators', desc: 'Compute running pace, time or distance', featured: true, icon: 'stopwatch', working: true },
  { id: 'race-predictor',      name: 'Race Predictor',       cat: 'sports', group: 'calculators', desc: '5K → 10K, half, marathon estimates (Riegel)', icon: 'target', working: true },
  { id: 'vo2max-estimator',    name: 'VO₂max Estimator',     cat: 'sports', group: 'calculators', desc: 'Cooper test or VDOT-based aerobic capacity', icon: 'gauge', working: true },
  { id: 'heart-rate-zones',    name: 'Heart-Rate Zones',     cat: 'sports', group: 'calculators', desc: 'Karvonen + MAF training zones', icon: 'heart', working: true },
  { id: 'calorie-burn',        name: 'Calorie Burn',         cat: 'sports', group: 'calculators', desc: 'Estimate kcal from distance, weight, pace', icon: 'bolt', working: true },
  { id: 'split-calculator',    name: 'Split Calculator',     cat: 'sports', group: 'calculators', desc: 'Even or negative splits for any target time', icon: 'clock', working: true },
  { id: 'stride-cadence',      name: 'Stride & Cadence',     cat: 'sports', group: 'calculators', desc: 'Stride length, cadence and weekly mileage', icon: 'ruler', working: true },
  { id: 'hydration-planner',   name: 'Hydration Planner',    cat: 'sports', group: 'calculators', desc: 'Fluid + sodium plan by duration & temperature', icon: 'droplet', working: true },
  { id: 'training-load',       name: 'Training Load (ACWR)', cat: 'sports', group: 'calculators', desc: 'Acute:chronic ratio for injury risk', icon: 'chart', working: true },

  { id: 'gpx-viewer',          name: 'GPX Viewer',           cat: 'sports', group: 'routes', desc: 'Map your run with elevation profile', featured: true, icon: 'map', working: true },
  { id: 'route-elevation',     name: 'Elevation Chart',      cat: 'sports', group: 'routes', desc: 'Export elevation profile as a PNG', icon: 'mountain', working: true },
  { id: 'gpx-merger',          name: 'GPX Merger',           cat: 'sports', group: 'routes', desc: 'Combine multiple GPX tracks into one', icon: 'merge', working: true },

  { id: 'gpx-trimmer',         name: 'GPX Trimmer',          cat: 'sports', group: 'files', desc: 'Hide your home address by clipping start/end', icon: 'crop', working: true },
  { id: 'gpx-to-geojson',      name: 'GPX to GeoJSON',       cat: 'sports', group: 'files', desc: 'Convert GPS tracks to GeoJSON', icon: 'swap', working: true },
  { id: 'tcx-to-gpx',          name: 'TCX to GPX',           cat: 'sports', group: 'files', desc: 'Convert Garmin TCX exports to GPX', icon: 'swap', working: true },
  { id: 'fit-to-gpx',          name: 'FIT to GPX',           cat: 'sports', group: 'files', desc: 'Convert Garmin/Wahoo FIT files to GPX', icon: 'swap', working: true },
  { id: 'strip-gps-metadata',  name: 'Strip GPS Metadata',   cat: 'sports', group: 'files', desc: 'Remove GPS EXIF tags from photos', icon: 'lock', working: true },

  { id: 'activity-share',      name: 'Activity Share Card',  cat: 'sports', group: 'share', desc: 'Transparent PNG of your route + stats — Strava-style, free', featured: true, icon: 'image', working: true },
  { id: 'screenshot-bg-remove',name: 'Screenshot BG Remover',cat: 'sports', group: 'share', desc: 'Turn a Strava share screenshot into a transparent PNG', featured: true, icon: 'erase', working: true },
];

window.CATEGORIES = [
  { id: 'pdf',       name: 'PDF Tools',   short: 'PDF',     tint: '#7c3aed', soft: '#efe8ff', desc: 'Solve your PDF problems',    featured: 'Merge PDF' },
  { id: 'image',     name: 'Image Tools', short: 'Image',   tint: '#ea580c', soft: '#ffede0', desc: 'Solve your image problems',  featured: 'Remove BG' },
  { id: 'converter', name: 'Converter',   short: 'Convert', tint: '#0e9488', soft: '#d9f5f1', desc: 'Swap formats in one click',  featured: 'HEIC to JPG' },
  { id: 'file',      name: 'File Tools',  short: 'Files',   tint: '#2563eb', soft: '#e4ecff', desc: 'Solve your file problems',   featured: 'Split Excel' },
  { id: 'text',      name: 'Text Tools',  short: 'Text',    tint: '#d946ef', soft: '#fae8ff', desc: 'Transform and generate text',        featured: 'Case Converter' },
  { id: 'developer', name: 'Developer',   short: 'Dev',     tint: '#f59e0b', soft: '#fef3c7', desc: 'CSS generators & code tools',        featured: 'CSS Gradient' },
  { id: 'sports',    name: 'Sports',      short: 'Sports',  tint: '#16a34a', soft: '#dcfce7', desc: 'Train smarter — pace, GPS, race day', featured: 'Pace Calculator' },
];

// Sub-categories shown on the dedicated Sports page. Each tool has a `group`
// field matching one of these ids.
window.SPORT_GROUPS = [
  { id: 'calculators', name: 'Calculators',     desc: 'Pace, zones, predictors, training load',  icon: 'stopwatch', tint: '#16a34a' },
  { id: 'routes',      name: 'Routes & Maps',   desc: 'GPX viewer, elevation, merger',            icon: 'map',       tint: '#0d9488' },
  { id: 'files',       name: 'Files & Privacy', desc: 'GPS file conversion + EXIF privacy',       icon: 'swap',      tint: '#2563eb' },
  { id: 'share',       name: 'Share & Posters', desc: 'Transparent activity cards for Stories',   icon: 'image',     tint: '#ea580c' },
];

// Home page hides Sports — it has its own dedicated page at #/sports.
window.HOME_CATEGORIES = window.CATEGORIES.filter((c) => c.id !== 'sports');
window.HOME_TOOLS = () => window.TOOLS.filter((t) => t.cat !== 'sports');

// Preserve the baked-in defaults so DB rows can be diffed against them and so
// we have a fallback if Supabase is unreachable.
window.TOOLS_BAKED = window.TOOLS.slice();
window.TOOLS_VERSION = 0;

// Fetch tool metadata from the public.list_tools() RPC and merge over the
// baked-in defaults. DB wins for name/desc/icon/cat/sort/featured/working;
// hidden rows drop out entirely. Sort by DB sort_order.
window.refreshTools = async function refreshTools() {
  const sb = window.getSupabase?.();
  if (!sb) return false;
  const { data, error } = await sb.rpc('list_tools');
  if (error || !Array.isArray(data)) return false;
  const byId = {};
  for (const r of data) byId[r.tool_id] = r;
  const merged = [];
  for (const baked of window.TOOLS_BAKED) {
    const db = byId[baked.id];
    if (!db) { merged.push(baked); continue; }
    merged.push({
      ...baked,
      name:     db.name        || baked.name,
      desc:     db.description || baked.desc,
      icon:     db.icon        || baked.icon,
      cat:      db.category    || baked.cat,
      featured: db.featured ?? baked.featured ?? false,
      working:  db.working  ?? baked.working ?? false,
      slug:     db.slug || baked.id,
      _sort:    db.sort_order ?? 999,
    });
  }
  merged.sort((a, b) => (a._sort ?? 999) - (b._sort ?? 999));
  window.TOOLS = merged;
  window.TOOLS_VERSION++;
  window.dispatchEvent(new CustomEvent('mm-tools-changed'));
  return true;
};

// React hook: returns the current tools list + a version counter, re-rendering
// whenever refreshTools() mutates window.TOOLS.
window.useTools = function useTools() {
  const [v, setV] = React.useState(window.TOOLS_VERSION);
  React.useEffect(() => {
    const onChange = () => setV(window.TOOLS_VERSION);
    window.addEventListener('mm-tools-changed', onChange);
    return () => window.removeEventListener('mm-tools-changed', onChange);
  }, []);
  return [window.TOOLS, v];
};
