"use client";

import { useState, useRef, useEffect } from "react";

// ==================== WEB TOOLS ====================

// Color Picker Tool
function ColorPicker() {
  const [color, setColor] = useState("#6366f1");
  const [copied, setCopied] = useState("");

  const hexToRgb = (hex: string) => {
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    return { r, g, b, str: `rgb(${r}, ${g}, ${b})` };
  };

  const hexToHsl = (hex: string) => {
    const { r, g, b } = hexToRgb(hex);
    const rNorm = r / 255, gNorm = g / 255, bNorm = b / 255;
    const max = Math.max(rNorm, gNorm, bNorm), min = Math.min(rNorm, gNorm, bNorm);
    let h = 0, s = 0;
    const l = (max + min) / 2;
    if (max !== min) {
      const d = max - min;
      s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
      switch (max) {
        case rNorm: h = ((gNorm - bNorm) / d + (gNorm < bNorm ? 6 : 0)) / 6; break;
        case gNorm: h = ((bNorm - rNorm) / d + 2) / 6; break;
        case bNorm: h = ((rNorm - gNorm) / d + 4) / 6; break;
      }
    }
    return `hsl(${Math.round(h * 360)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%)`;
  };

  const copy = (val: string, type: string) => {
    navigator.clipboard.writeText(val);
    setCopied(type);
    setTimeout(() => setCopied(""), 1500);
  };

  const formats = [
    { type: "HEX", value: color.toUpperCase() },
    { type: "RGB", value: hexToRgb(color).str },
    { type: "HSL", value: hexToHsl(color) },
  ];

  return (
    <div className="space-y-4">
      <div
        className="w-full h-32 rounded-xl border border-border cursor-pointer transition-transform hover:scale-[1.02] shadow-inner"
        style={{ backgroundColor: color }}
        onClick={() => copy(color, "preview")}
      />
      <input
        type="color"
        value={color}
        onChange={(e) => setColor(e.target.value)}
        className="w-full h-12 rounded-lg cursor-pointer"
      />
      <div className="space-y-2">
        {formats.map((f) => (
          <div
            key={f.type}
            onClick={() => copy(f.value, f.type)}
            className="flex items-center justify-between p-3 rounded-lg bg-surface-elevated cursor-pointer hover:bg-surface-hover transition-colors"
          >
            <span className="text-text-muted text-xs font-semibold">{f.type}</span>
            <code className="text-text-primary text-sm">{f.value}</code>
            {copied === f.type && <span className="text-success text-xs">✓</span>}
          </div>
        ))}
      </div>
    </div>
  );
}

// Gradient Generator
function GradientGenerator() {
  const [color1, setColor1] = useState("#6366f1");
  const [color2, setColor2] = useState("#22d3ee");
  const [angle, setAngle] = useState(135);
  const [copied, setCopied] = useState(false);

  const gradient = `linear-gradient(${angle}deg, ${color1}, ${color2})`;
  const css = `background: ${gradient};`;

  const copy = () => {
    navigator.clipboard.writeText(css);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  return (
    <div className="space-y-4">
      <div
        className="w-full h-32 rounded-xl border border-border cursor-pointer hover:scale-[1.02] transition-transform"
        style={{ background: gradient }}
        onClick={copy}
      />
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label className="text-xs text-text-muted block mb-1">Color 1</label>
          <input
            type="color"
            value={color1}
            onChange={(e) => setColor1(e.target.value)}
            className="w-full h-10 rounded-lg cursor-pointer"
          />
        </div>
        <div>
          <label className="text-xs text-text-muted block mb-1">Color 2</label>
          <input
            type="color"
            value={color2}
            onChange={(e) => setColor2(e.target.value)}
            className="w-full h-10 rounded-lg cursor-pointer"
          />
        </div>
      </div>
      <div>
        <label className="text-xs text-text-muted block mb-1">Angle: {angle}°</label>
        <input
          type="range"
          min="0"
          max="360"
          value={angle}
          onChange={(e) => setAngle(parseInt(e.target.value))}
          className="w-full"
        />
      </div>
      <button
        onClick={copy}
        className="w-full py-2.5 bg-primary text-white font-semibold rounded-xl text-sm"
      >
        {copied ? "✓ Copied!" : "Copy CSS"}
      </button>
    </div>
  );
}

// Password Generator
function PasswordGenerator() {
  const [password, setPassword] = useState("");
  const [length, setLength] = useState(16);
  const [options, setOptions] = useState({
    uppercase: true,
    lowercase: true,
    numbers: true,
    symbols: true,
  });
  const [copied, setCopied] = useState(false);

  const generate = () => {
    let chars = "";
    if (options.uppercase) chars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if (options.lowercase) chars += "abcdefghijklmnopqrstuvwxyz";
    if (options.numbers) chars += "0123456789";
    if (options.symbols) chars += "!@#$%^&*()_+-=[]{}|;:,.<>?";
    if (!chars) chars = "abcdefghijklmnopqrstuvwxyz";
    
    let result = "";
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setPassword(result);
  };

  const strength = () => {
    let score = 0;
    if (length >= 12) score++;
    if (length >= 16) score++;
    if (options.uppercase && options.lowercase) score++;
    if (options.numbers) score++;
    if (options.symbols) score++;
    if (score <= 2) return { label: "Weak", color: "bg-red-500", width: "33%" };
    if (score <= 3) return { label: "Medium", color: "bg-yellow-500", width: "66%" };
    return { label: "Strong", color: "bg-green-500", width: "100%" };
  };

  return (
    <div className="space-y-4">
      <div className="relative">
        <input
          type="text"
          value={password}
          readOnly
          placeholder="Click generate..."
          className="w-full pr-12 font-mono text-sm"
        />
        {password && (
          <button
            onClick={() => { navigator.clipboard.writeText(password); setCopied(true); setTimeout(() => setCopied(false), 1500); }}
            className="absolute right-2 top-1/2 -translate-y-1/2 p-2 text-text-muted hover:text-text-primary"
          >
            {copied ? "✓" : "📋"}
          </button>
        )}
      </div>
      <div className="h-2 bg-surface-elevated rounded-full overflow-hidden">
        <div className={`h-full ${strength().color} transition-all`} style={{ width: strength().width }} />
      </div>
      <div className="flex justify-between text-xs">
        <span className="text-text-muted">Length: {length}</span>
        <span className={strength().color.replace("bg-", "text-")}>{strength().label}</span>
      </div>
      <input
        type="range"
        min="8"
        max="32"
        value={length}
        onChange={(e) => setLength(parseInt(e.target.value))}
        className="w-full"
      />
      <div className="grid grid-cols-2 gap-2">
        {Object.entries(options).map(([key, val]) => (
          <label key={key} className="flex items-center gap-2 text-xs cursor-pointer">
            <input
              type="checkbox"
              checked={val}
              onChange={(e) => setOptions({ ...options, [key]: e.target.checked })}
              className="rounded"
            />
            <span className="text-text-secondary capitalize">{key}</span>
          </label>
        ))}
      </div>
      <button onClick={generate} className="w-full py-2.5 bg-gradient-to-r from-primary to-accent text-white font-semibold rounded-xl text-sm">
        Generate Password
      </button>
    </div>
  );
}

// Lorem Ipsum Generator
function LoremGenerator() {
  const [paragraphs, setParagraphs] = useState(2);
  const [text, setText] = useState("");
  const [copied, setCopied] = useState(false);

  const loremWords = [
    "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit",
    "sed", "do", "eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore",
    "magna", "aliqua", "enim", "ad", "minim", "veniam", "quis", "nostrud",
    "exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", "ea", "commodo",
    "consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate"
  ];

  const generate = () => {
    const result = [];
    for (let p = 0; p < paragraphs; p++) {
      const sentences = [];
      for (let s = 0; s < 4 + Math.floor(Math.random() * 3); s++) {
        const words = [];
        for (let w = 0; w < 8 + Math.floor(Math.random() * 8); w++) {
          words.push(loremWords[Math.floor(Math.random() * loremWords.length)]);
        }
        words[0] = words[0].charAt(0).toUpperCase() + words[0].slice(1);
        sentences.push(words.join(" ") + ".");
      }
      result.push(sentences.join(" "));
    }
    setText(result.join("\n\n"));
  };

  return (
    <div className="space-y-4">
      <div>
        <label className="text-xs text-text-muted mb-1 block">Paragraphs: {paragraphs}</label>
        <input type="range" min="1" max="5" value={paragraphs} onChange={(e) => setParagraphs(parseInt(e.target.value))} className="w-full" />
      </div>
      <button onClick={generate} className="w-full py-2.5 bg-gradient-to-r from-cyan-500 to-blue-500 text-white font-semibold rounded-xl text-sm">
        Generate Text
      </button>
      {text && (
        <>
          <div className="max-h-32 overflow-y-auto p-3 rounded-lg bg-surface-elevated text-xs text-text-secondary">{text}</div>
          <button
            onClick={() => { navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 1500); }}
            className="w-full py-2 border border-border rounded-xl text-xs"
          >
            {copied ? "✓ Copied!" : "Copy Text"}
          </button>
        </>
      )}
    </div>
  );
}

// ==================== IMAGE TOOLS ====================

// Image Resizer
function ImageResizer() {
  const [image, setImage] = useState<string | null>(null);
  const [width, setWidth] = useState(800);
  const [height, setHeight] = useState(600);
  const [maintainRatio, setMaintainRatio] = useState(true);
  const [originalRatio, setOriginalRatio] = useState(1);
  const canvasRef = useRef<HTMLCanvasElement>(null);

  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        const img = new Image();
        img.onload = () => {
          setWidth(img.width);
          setHeight(img.height);
          setOriginalRatio(img.width / img.height);
        };
        img.src = event.target?.result as string;
        setImage(event.target?.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleWidthChange = (w: number) => {
    setWidth(w);
    if (maintainRatio) setHeight(Math.round(w / originalRatio));
  };

  const handleHeightChange = (h: number) => {
    setHeight(h);
    if (maintainRatio) setWidth(Math.round(h * originalRatio));
  };

  const downloadResized = () => {
    if (!image || !canvasRef.current) return;
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    canvas.width = width;
    canvas.height = height;

    const img = new Image();
    img.onload = () => {
      ctx.drawImage(img, 0, 0, width, height);
      const link = document.createElement("a");
      link.download = `resized-${width}x${height}.png`;
      link.href = canvas.toDataURL("image/png");
      link.click();
    };
    img.src = image;
  };

  return (
    <div className="space-y-4">
      <canvas ref={canvasRef} className="hidden" />
      <label className="block w-full p-6 border-2 border-dashed border-border rounded-xl text-center cursor-pointer hover:border-primary/50 transition-colors">
        <input type="file" accept="image/*" onChange={handleImageUpload} className="hidden" />
        {image ? (
          <img src={image} alt="Preview" className="max-h-24 mx-auto rounded" />
        ) : (
          <span className="text-text-muted text-sm">📷 Click to upload image</span>
        )}
      </label>
      {image && (
        <>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs text-text-muted block mb-1">Width (px)</label>
              <input type="number" value={width} onChange={(e) => handleWidthChange(parseInt(e.target.value) || 0)} className="w-full" />
            </div>
            <div>
              <label className="text-xs text-text-muted block mb-1">Height (px)</label>
              <input type="number" value={height} onChange={(e) => handleHeightChange(parseInt(e.target.value) || 0)} className="w-full" />
            </div>
          </div>
          <label className="flex items-center gap-2 text-xs cursor-pointer">
            <input type="checkbox" checked={maintainRatio} onChange={(e) => setMaintainRatio(e.target.checked)} className="rounded" />
            <span className="text-text-secondary">Maintain aspect ratio</span>
          </label>
          <button onClick={downloadResized} className="w-full py-2.5 bg-gradient-to-r from-green-500 to-emerald-500 text-white font-semibold rounded-xl text-sm">
            Download Resized
          </button>
        </>
      )}
    </div>
  );
}

// Image Compressor
function ImageCompressor() {
  const [image, setImage] = useState<string | null>(null);
  const [quality, setQuality] = useState(80);
  const [originalSize, setOriginalSize] = useState(0);
  const [compressedSize, setCompressedSize] = useState(0);
  const canvasRef = useRef<HTMLCanvasElement>(null);

  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setOriginalSize(file.size);
      const reader = new FileReader();
      reader.onload = (event) => {
        setImage(event.target?.result as string);
        compressImage(event.target?.result as string, quality);
      };
      reader.readAsDataURL(file);
    }
  };

  const compressImage = (src: string, q: number) => {
    const img = new Image();
    img.onload = () => {
      const canvas = canvasRef.current;
      if (!canvas) return;
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext("2d");
      if (!ctx) return;
      ctx.drawImage(img, 0, 0);
      const dataUrl = canvas.toDataURL("image/jpeg", q / 100);
      const base64 = dataUrl.split(",")[1];
      setCompressedSize(Math.round((base64.length * 3) / 4));
    };
    img.src = src;
  };

  useEffect(() => {
    if (image) compressImage(image, quality);
  }, [quality, image]);

  const download = () => {
    if (!canvasRef.current) return;
    const link = document.createElement("a");
    link.download = `compressed-${quality}.jpg`;
    link.href = canvasRef.current.toDataURL("image/jpeg", quality / 100);
    link.click();
  };

  const formatSize = (bytes: number) => {
    if (bytes < 1024) return bytes + " B";
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB";
    return (bytes / 1024 / 1024).toFixed(1) + " MB";
  };

  const savings = originalSize > 0 ? Math.round((1 - compressedSize / originalSize) * 100) : 0;

  return (
    <div className="space-y-4">
      <canvas ref={canvasRef} className="hidden" />
      <label className="block w-full p-6 border-2 border-dashed border-border rounded-xl text-center cursor-pointer hover:border-primary/50 transition-colors">
        <input type="file" accept="image/*" onChange={handleImageUpload} className="hidden" />
        {image ? (
          <img src={image} alt="Preview" className="max-h-24 mx-auto rounded" />
        ) : (
          <span className="text-text-muted text-sm">📷 Click to upload image</span>
        )}
      </label>
      {image && (
        <>
          <div>
            <div className="flex justify-between text-xs mb-1">
              <span className="text-text-muted">Quality: {quality}%</span>
              <span className="text-success font-semibold">-{savings}%</span>
            </div>
            <input type="range" min="10" max="100" value={quality} onChange={(e) => setQuality(parseInt(e.target.value))} className="w-full" />
          </div>
          <div className="grid grid-cols-2 gap-3 text-center">
            <div className="p-3 rounded-lg bg-surface-elevated">
              <p className="text-xs text-text-muted">Original</p>
              <p className="text-sm font-semibold text-text-primary">{formatSize(originalSize)}</p>
            </div>
            <div className="p-3 rounded-lg bg-success/10">
              <p className="text-xs text-text-muted">Compressed</p>
              <p className="text-sm font-semibold text-success">{formatSize(compressedSize)}</p>
            </div>
          </div>
          <button onClick={download} className="w-full py-2.5 bg-gradient-to-r from-purple-500 to-pink-500 text-white font-semibold rounded-xl text-sm">
            Download Compressed
          </button>
        </>
      )}
    </div>
  );
}

// Image to Base64
function ImageToBase64() {
  const [base64, setBase64] = useState("");
  const [copied, setCopied] = useState(false);

  const handleUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => setBase64(event.target?.result as string);
      reader.readAsDataURL(file);
    }
  };

  const copy = () => {
    navigator.clipboard.writeText(base64);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  return (
    <div className="space-y-4">
      <label className="block w-full p-6 border-2 border-dashed border-border rounded-xl text-center cursor-pointer hover:border-primary/50">
        <input type="file" accept="image/*" onChange={handleUpload} className="hidden" />
        <span className="text-text-muted text-sm">📷 Upload image</span>
      </label>
      {base64 && (
        <>
          <div className="p-3 rounded-lg bg-surface-elevated max-h-32 overflow-y-auto">
            <code className="text-xs text-text-secondary break-all">{base64.substring(0, 200)}...</code>
          </div>
          <p className="text-xs text-text-muted text-center">{base64.length.toLocaleString()} characters</p>
          <button onClick={copy} className="w-full py-2.5 bg-primary text-white font-semibold rounded-xl text-sm">
            {copied ? "✓ Copied!" : "Copy Base64"}
          </button>
        </>
      )}
    </div>
  );
}

// ==================== VIDEO TOOLS ====================

// Video Thumbnail Extractor
function VideoThumbnail() {
  const [video, setVideo] = useState<string | null>(null);
  const [thumbnails, setThumbnails] = useState<string[]>([]);
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);

  const handleUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setVideo(URL.createObjectURL(file));
      setThumbnails([]);
    }
  };

  const extractThumbnails = () => {
    const videoEl = videoRef.current;
    const canvas = canvasRef.current;
    if (!videoEl || !canvas) return;

    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    const duration = videoEl.duration;
    const times = [0, duration * 0.25, duration * 0.5, duration * 0.75];
    const newThumbnails: string[] = [];

    let index = 0;
    const captureFrame = () => {
      if (index >= times.length) {
        setThumbnails(newThumbnails);
        return;
      }
      videoEl.currentTime = times[index];
    };

    videoEl.onseeked = () => {
      canvas.width = videoEl.videoWidth;
      canvas.height = videoEl.videoHeight;
      ctx.drawImage(videoEl, 0, 0);
      newThumbnails.push(canvas.toDataURL("image/jpeg", 0.8));
      index++;
      captureFrame();
    };

    captureFrame();
  };

  const downloadThumb = (dataUrl: string, i: number) => {
    const link = document.createElement("a");
    link.download = `thumbnail-${i + 1}.jpg`;
    link.href = dataUrl;
    link.click();
  };

  return (
    <div className="space-y-4">
      <canvas ref={canvasRef} className="hidden" />
      <video ref={videoRef} src={video || ""} className="hidden" />
      <label className="block w-full p-6 border-2 border-dashed border-border rounded-xl text-center cursor-pointer hover:border-primary/50">
        <input type="file" accept="video/*" onChange={handleUpload} className="hidden" />
        <span className="text-text-muted text-sm">🎬 Upload video</span>
      </label>
      {video && (
        <>
          <video src={video} controls className="w-full rounded-lg" onLoadedMetadata={extractThumbnails} />
          {thumbnails.length > 0 && (
            <div className="grid grid-cols-2 gap-2">
              {thumbnails.map((thumb, i) => (
                <img
                  key={i}
                  src={thumb}
                  alt={`Thumbnail ${i + 1}`}
                  className="rounded cursor-pointer hover:opacity-80"
                  onClick={() => downloadThumb(thumb, i)}
                />
              ))}
            </div>
          )}
        </>
      )}
    </div>
  );
}

// ==================== GRAPHIC TOOLS ====================

// Box Shadow Generator
function BoxShadowGenerator() {
  const [hOffset, setHOffset] = useState(5);
  const [vOffset, setVOffset] = useState(5);
  const [blur, setBlur] = useState(15);
  const [spread, setSpread] = useState(0);
  const [color, setColor] = useState("#000000");
  const [opacity, setOpacity] = useState(25);
  const [inset, setInset] = useState(false);
  const [copied, setCopied] = useState(false);

  const rgbaColor = () => {
    const r = parseInt(color.slice(1, 3), 16);
    const g = parseInt(color.slice(3, 5), 16);
    const b = parseInt(color.slice(5, 7), 16);
    return `rgba(${r}, ${g}, ${b}, ${opacity / 100})`;
  };

  const shadow = `${inset ? "inset " : ""}${hOffset}px ${vOffset}px ${blur}px ${spread}px ${rgbaColor()}`;
  const css = `box-shadow: ${shadow};`;

  return (
    <div className="space-y-4">
      <div
        className="w-full h-24 rounded-xl bg-surface-elevated flex items-center justify-center"
      >
        <div className="w-20 h-20 bg-white rounded-lg" style={{ boxShadow: shadow }} />
      </div>
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label className="text-xs text-text-muted">H-Offset: {hOffset}px</label>
          <input type="range" min="-50" max="50" value={hOffset} onChange={(e) => setHOffset(parseInt(e.target.value))} className="w-full" />
        </div>
        <div>
          <label className="text-xs text-text-muted">V-Offset: {vOffset}px</label>
          <input type="range" min="-50" max="50" value={vOffset} onChange={(e) => setVOffset(parseInt(e.target.value))} className="w-full" />
        </div>
        <div>
          <label className="text-xs text-text-muted">Blur: {blur}px</label>
          <input type="range" min="0" max="100" value={blur} onChange={(e) => setBlur(parseInt(e.target.value))} className="w-full" />
        </div>
        <div>
          <label className="text-xs text-text-muted">Spread: {spread}px</label>
          <input type="range" min="-50" max="50" value={spread} onChange={(e) => setSpread(parseInt(e.target.value))} className="w-full" />
        </div>
      </div>
      <div className="flex items-center gap-3">
        <input type="color" value={color} onChange={(e) => setColor(e.target.value)} className="w-10 h-10 rounded cursor-pointer" />
        <div className="flex-1">
          <label className="text-xs text-text-muted">Opacity: {opacity}%</label>
          <input type="range" min="0" max="100" value={opacity} onChange={(e) => setOpacity(parseInt(e.target.value))} className="w-full" />
        </div>
      </div>
      <label className="flex items-center gap-2 text-xs cursor-pointer">
        <input type="checkbox" checked={inset} onChange={(e) => setInset(e.target.checked)} className="rounded" />
        <span className="text-text-secondary">Inset shadow</span>
      </label>
      <button
        onClick={() => { navigator.clipboard.writeText(css); setCopied(true); setTimeout(() => setCopied(false), 1500); }}
        className="w-full py-2.5 bg-gradient-to-r from-amber-500 to-orange-500 text-white font-semibold rounded-xl text-sm"
      >
        {copied ? "✓ Copied!" : "Copy CSS"}
      </button>
    </div>
  );
}

// Border Radius Generator
function BorderRadiusGenerator() {
  const [tl, setTl] = useState(20);
  const [tr, setTr] = useState(20);
  const [br, setBr] = useState(20);
  const [bl, setBl] = useState(20);
  const [linked, setLinked] = useState(true);
  const [copied, setCopied] = useState(false);

  const handleChange = (setter: (v: number) => void, value: number) => {
    if (linked) {
      setTl(value); setTr(value); setBr(value); setBl(value);
    } else {
      setter(value);
    }
  };

  const css = `border-radius: ${tl}px ${tr}px ${br}px ${bl}px;`;

  return (
    <div className="space-y-4">
      <div className="w-full h-32 bg-gradient-to-br from-primary to-accent flex items-center justify-center" style={{ borderRadius: `${tl}px ${tr}px ${br}px ${bl}px` }}>
        <span className="text-white text-sm font-semibold">Preview</span>
      </div>
      <label className="flex items-center gap-2 text-xs cursor-pointer">
        <input type="checkbox" checked={linked} onChange={(e) => setLinked(e.target.checked)} className="rounded" />
        <span className="text-text-secondary">Link corners</span>
      </label>
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label className="text-xs text-text-muted">Top Left: {tl}px</label>
          <input type="range" min="0" max="100" value={tl} onChange={(e) => handleChange(setTl, parseInt(e.target.value))} className="w-full" />
        </div>
        <div>
          <label className="text-xs text-text-muted">Top Right: {tr}px</label>
          <input type="range" min="0" max="100" value={tr} onChange={(e) => handleChange(setTr, parseInt(e.target.value))} className="w-full" />
        </div>
        <div>
          <label className="text-xs text-text-muted">Bottom Left: {bl}px</label>
          <input type="range" min="0" max="100" value={bl} onChange={(e) => handleChange(setBl, parseInt(e.target.value))} className="w-full" />
        </div>
        <div>
          <label className="text-xs text-text-muted">Bottom Right: {br}px</label>
          <input type="range" min="0" max="100" value={br} onChange={(e) => handleChange(setBr, parseInt(e.target.value))} className="w-full" />
        </div>
      </div>
      <button
        onClick={() => { navigator.clipboard.writeText(css); setCopied(true); setTimeout(() => setCopied(false), 1500); }}
        className="w-full py-2.5 bg-gradient-to-r from-pink-500 to-rose-500 text-white font-semibold rounded-xl text-sm"
      >
        {copied ? "✓ Copied!" : "Copy CSS"}
      </button>
    </div>
  );
}

// ==================== MAIN COMPONENT ====================

const tools = [
  { id: "color", name: "Color Picker", icon: "🎨", category: "web", component: ColorPicker },
  { id: "gradient", name: "Gradient Generator", icon: "🌈", category: "web", component: GradientGenerator },
  { id: "password", name: "Password Generator", icon: "🔐", category: "web", component: PasswordGenerator },
  { id: "lorem", name: "Lorem Ipsum", icon: "📝", category: "web", component: LoremGenerator },
  { id: "resize", name: "Image Resizer", icon: "📐", category: "image", component: ImageResizer },
  { id: "compress", name: "Image Compressor", icon: "🗜️", category: "image", component: ImageCompressor },
  { id: "base64", name: "Image to Base64", icon: "🔣", category: "image", component: ImageToBase64 },
  { id: "thumbnail", name: "Video Thumbnails", icon: "🎬", category: "video", component: VideoThumbnail },
  { id: "shadow", name: "Box Shadow", icon: "🖼️", category: "graphic", component: BoxShadowGenerator },
  { id: "radius", name: "Border Radius", icon: "⬜", category: "graphic", component: BorderRadiusGenerator },
];

export default function ToolsSection() {
  const [activeCategory, setActiveCategory] = useState("all");

  const categories = [
    { id: "all", name: "All Tools", icon: "🛠️" },
    { id: "web", name: "Web Tools", icon: "🌐" },
    { id: "image", name: "Image Tools", icon: "🖼️" },
    { id: "video", name: "Video Tools", icon: "🎬" },
    { id: "graphic", name: "Graphic Tools", icon: "✨" },
  ];

  const filteredTools = activeCategory === "all" 
    ? tools 
    : tools.filter(t => t.category === activeCategory);

  return (
    <section id="tools" className="py-24 relative overflow-hidden">
      <div className="absolute inset-0 hero-gradient opacity-30" />

      <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="text-center mb-12">
          <span className="inline-block px-4 py-1.5 text-xs font-semibold uppercase tracking-wider text-cyan-400 bg-cyan-500/10 rounded-full mb-4">
            Free Tools
          </span>
          <h2 className="text-4xl sm:text-5xl font-bold text-text-primary mb-4">
            Developer <span className="gradient-text">Utilities</span>
          </h2>
          <p className="text-text-muted max-w-2xl mx-auto text-lg">
            Professional tools for web development, image processing, video editing, and graphic design — all free!
          </p>
        </div>

        {/* Category Filter */}
        <div className="flex flex-wrap justify-center gap-2 mb-10">
          {categories.map((cat) => (
            <button
              key={cat.id}
              onClick={() => setActiveCategory(cat.id)}
              className={`px-4 py-2 rounded-xl text-sm font-medium transition-all flex items-center gap-2 ${
                activeCategory === cat.id
                  ? "bg-primary text-white shadow-lg shadow-primary/25"
                  : "bg-surface-card text-text-secondary hover:text-text-primary border border-border"
              }`}
            >
              <span>{cat.icon}</span>
              {cat.name}
            </button>
          ))}
        </div>

        {/* Tools Grid */}
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {filteredTools.map((tool) => {
            const ToolComponent = tool.component;
            return (
              <div key={tool.id} className="glass rounded-2xl p-6">
                <h3 className="text-lg font-bold text-text-primary mb-4 flex items-center gap-2">
                  <span className="text-2xl">{tool.icon}</span>
                  {tool.name}
                </h3>
                <ToolComponent />
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}
