// Instagram Post Mockup — create a realistic IG post preview and export as PNG.

window.TOOL_HANDLERS['instagram-post'] = function InstagramPostTool() {
  const [photo, setPhoto] = React.useState(null);
  const [photoUrl, setPhotoUrl] = React.useState('');
  const [profilePic, setProfilePic] = React.useState(null);
  const [profilePicUrl, setProfilePicUrl] = React.useState('');
  const [username, setUsername] = React.useState('your_username');
  const [likes, setLikes] = React.useState(142);
  const [caption, setCaption] = React.useState('Living my best life');
  const [timeAgo, setTimeAgo] = React.useState('2 hours ago');
  const imgRef = React.useRef(null);
  const profileImgRef = React.useRef(null);
  const cardRef = React.useRef(null);

  const handlePhoto = async (f) => {
    if (!f || !f.type.startsWith('image/')) return;
    const { img, url } = await window.loadImageFromFile(f);
    imgRef.current = img;
    setPhoto(f);
    setPhotoUrl(url);
  };

  const handleProfilePic = async (f) => {
    if (!f || !f.type.startsWith('image/')) return;
    const { img, url } = await window.loadImageFromFile(f);
    profileImgRef.current = img;
    setProfilePic(f);
    setProfilePicUrl(url);
  };

  // SVG icons for Instagram action bar
  const HeartIcon = () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
    </svg>
  );
  const CommentIcon = () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
    </svg>
  );
  const ShareIcon = () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>
    </svg>
  );
  const BookmarkIcon = () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>
    </svg>
  );

  const exportPng = async () => {
    if (!imgRef.current) return;
    const cardW = 440;
    const headerH = 58;
    const imgH = cardW; // square
    const actionsH = 44;
    const likesH = 24;
    const captionH = caption ? 22 : 0;
    const timeH = 20;
    const padBottom = 14;
    const totalH = headerH + imgH + actionsH + likesH + captionH + timeH + padBottom;

    const c = document.createElement('canvas');
    c.width = cardW;
    c.height = totalH;
    const ctx = c.getContext('2d');

    // White background
    ctx.fillStyle = '#ffffff';
    ctx.roundRect(0, 0, cardW, totalH, 0);
    ctx.fill();

    let y = 0;

    // Header
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, cardW, headerH);

    // Profile pic circle
    const ppSize = 34;
    const ppX = 14;
    const ppY = (headerH - ppSize) / 2;
    ctx.save();
    ctx.beginPath();
    ctx.arc(ppX + ppSize / 2, ppY + ppSize / 2, ppSize / 2, 0, Math.PI * 2);
    ctx.clip();
    if (profileImgRef.current) {
      ctx.drawImage(profileImgRef.current, ppX, ppY, ppSize, ppSize);
    } else {
      ctx.fillStyle = '#dbdbdb';
      ctx.fillRect(ppX, ppY, ppSize, ppSize);
    }
    ctx.restore();

    // Username in header
    ctx.fillStyle = '#262626';
    ctx.font = '600 14px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
    ctx.textBaseline = 'middle';
    ctx.fillText(username, ppX + ppSize + 12, headerH / 2);

    y = headerH;

    // Main image (square crop)
    const img = imgRef.current;
    const cropSize = Math.min(img.width, img.height);
    const sx = (img.width - cropSize) / 2;
    const sy = (img.height - cropSize) / 2;
    ctx.drawImage(img, sx, sy, cropSize, cropSize, 0, y, cardW, imgH);
    y += imgH;

    // Action icons row (just draw small symbols)
    const iconY = y + 10;
    ctx.strokeStyle = '#262626';
    ctx.lineWidth = 1.6;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    // Heart outline
    ctx.beginPath();
    const hx = 16, hy = iconY;
    ctx.moveTo(hx + 10, hy + 3);
    ctx.bezierCurveTo(hx + 10, hy + 1, hx + 7, hy - 1, hx + 5, hy + 2);
    ctx.bezierCurveTo(hx + 3, hy + 5, hx + 5, hy + 9, hx + 10, hy + 14);
    ctx.bezierCurveTo(hx + 15, hy + 9, hx + 17, hy + 5, hx + 15, hy + 2);
    ctx.bezierCurveTo(hx + 13, hy - 1, hx + 10, hy + 1, hx + 10, hy + 3);
    ctx.stroke();

    // Bookmark (right side)
    ctx.beginPath();
    const bx = cardW - 32, by = iconY;
    ctx.moveTo(bx, by); ctx.lineTo(bx, by + 16);
    ctx.lineTo(bx + 7, by + 11); ctx.lineTo(bx + 14, by + 16);
    ctx.lineTo(bx + 14, by); ctx.closePath();
    ctx.stroke();

    y += actionsH;

    // Likes
    ctx.fillStyle = '#262626';
    ctx.font = '600 14px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
    ctx.textBaseline = 'top';
    ctx.fillText(likes.toLocaleString() + ' likes', 14, y);
    y += likesH;

    // Caption
    if (caption) {
      ctx.font = '400 14px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
      ctx.fillStyle = '#262626';
      ctx.font = '600 14px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
      ctx.fillText(username, 14, y);
      const uWidth = ctx.measureText(username + ' ').width;
      ctx.font = '400 14px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
      ctx.fillText(caption, 14 + uWidth, y);
      y += captionH;
    }

    // Time ago
    ctx.fillStyle = '#8e8e8e';
    ctx.font = '400 11px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
    ctx.fillText(timeAgo, 14, y);

    c.toBlob((blob) => {
      if (blob) window.downloadBlob(blob, 'instagram-post.png');
    }, 'image/png');
  };

  if (!photo) {
    return <window.Dropzone onFile={handlePhoto} title="Drop a photo here" hint="create an Instagram post mockup" accept="image/*" />;
  }

  const cardStyle = {
    maxWidth: 440,
    margin: '0 auto',
    background: '#ffffff',
    borderRadius: 8,
    border: '1px solid #dbdbdb',
    overflow: 'hidden',
    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
    color: '#262626',
  };

  return (
    <div className="mini-tool">
      {/* Controls */}
      <div className="mini-row" style={{ gap: 12, marginBottom: 16, flexWrap: 'wrap', alignItems: 'flex-end' }}>
        <div className="mini-field" style={{ flex: 1, minWidth: 140 }}>
          <label className="mini-label">Username</label>
          <input className="mini-input" value={username}
                 onChange={(e) => setUsername(e.target.value)}
                 placeholder="username" />
        </div>
        <div className="mini-field" style={{ flex: '0 0 auto' }}>
          <label className="mini-label">Likes</label>
          <input type="number" className="mini-input" value={likes} min="0"
                 onChange={(e) => setLikes(Math.max(0, Number(e.target.value) || 0))}
                 style={{ width: 90 }} />
        </div>
        <div className="mini-field" style={{ flex: '0 0 auto' }}>
          <label className="mini-label">Time ago</label>
          <input className="mini-input" value={timeAgo}
                 onChange={(e) => setTimeAgo(e.target.value)}
                 style={{ width: 120 }} />
        </div>
        <div className="mini-field" style={{ flex: '0 0 auto' }}>
          <label className="mini-label">Profile pic</label>
          <label className="btn btn-secondary" style={{ cursor: 'pointer', fontSize: 12, padding: '6px 10px' }}>
            <window.Icon name="upload" size={12} /> {profilePic ? 'Change' : 'Upload'}
            <input type="file" accept="image/*" hidden
                   onChange={(e) => { if (e.target.files[0]) handleProfilePic(e.target.files[0]); }} />
          </label>
        </div>
      </div>
      <div className="mini-field" style={{ marginBottom: 16 }}>
        <label className="mini-label">Caption</label>
        <input className="mini-input" value={caption}
               onChange={(e) => setCaption(e.target.value)}
               placeholder="Write a caption..." />
      </div>

      {/* Live Preview Card */}
      <div ref={cardRef} style={cardStyle}>
        {/* Header */}
        <div style={{
          display: 'flex', alignItems: 'center', padding: '10px 14px',
          borderBottom: '1px solid #efefef',
        }}>
          <div style={{
            width: 34, height: 34, borderRadius: '50%', overflow: 'hidden',
            border: '1px solid #dbdbdb', flexShrink: 0,
            background: profilePicUrl ? 'none' : '#efefef',
          }}>
            {profilePicUrl && (
              <img src={profilePicUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            )}
          </div>
          <span style={{ fontWeight: 600, fontSize: 14, marginLeft: 12 }}>{username}</span>
          <span style={{ marginLeft: 'auto', fontSize: 18, letterSpacing: 2, color: '#262626', cursor: 'pointer' }}>...</span>
        </div>

        {/* Photo */}
        <div style={{ width: '100%', aspectRatio: '1/1', overflow: 'hidden', background: '#fafafa' }}>
          <img src={photoUrl} alt="" style={{
            width: '100%', height: '100%', objectFit: 'cover', display: 'block',
          }} />
        </div>

        {/* Action bar */}
        <div style={{
          display: 'flex', alignItems: 'center', padding: '10px 14px',
          gap: 16,
        }}>
          <HeartIcon /><CommentIcon /><ShareIcon />
          <span style={{ marginLeft: 'auto' }}><BookmarkIcon /></span>
        </div>

        {/* Likes */}
        <div style={{ padding: '0 14px', fontWeight: 600, fontSize: 14 }}>
          {likes.toLocaleString()} likes
        </div>

        {/* Caption */}
        {caption && (
          <div style={{ padding: '4px 14px 0', fontSize: 14, lineHeight: 1.4 }}>
            <span style={{ fontWeight: 600 }}>{username}</span>{' '}{caption}
          </div>
        )}

        {/* Time */}
        <div style={{ padding: '6px 14px 12px', fontSize: 11, color: '#8e8e8e', textTransform: 'uppercase' }}>
          {timeAgo}
        </div>
      </div>

      <div className="cmp-actions" style={{ marginTop: 16 }}>
        <button className="btn btn-secondary" onClick={() => {
          setPhoto(null); setPhotoUrl(''); imgRef.current = null;
        }}>
          <window.Icon name="upload" size={16} /> Another photo
        </button>
        <button className="btn btn-primary" onClick={exportPng}>
          <window.Icon name="download" size={16} /> Export as PNG
        </button>
      </div>
    </div>
  );
};
