// ─── Image source helpers ─────────────────────────────────────────────────────

// True if src is a self-contained data URL or absolute URL (safe to render)
const isAbsoluteSrc = (src) =>
  src && (src.startsWith('data:') || src.startsWith('http') || src.startsWith('//') || src.startsWith('blob:'));

// Filename from a relative path, e.g. "assets/logo.png" → "logo.png"
const basename = (src) => src.split('/').pop();

// ─── Single image upload — converts to base64, no API required ───────────────

function ImageUpload({ value, onChange, shape, uploadLabel }) {
  const [uploading, setUploading] = React.useState(false);
  const inputRef = React.useRef(null);

  const upload = (file) => {
    setUploading(true);
    const reader = new FileReader();
    reader.onload  = (ev) => { onChange(ev.target.result); setUploading(false); };
    reader.onerror = ()    => setUploading(false);
    reader.readAsDataURL(file);
  };

  const handleChange = (e) => {
    if (e.target.files[0]) upload(e.target.files[0]);
    e.target.value = '';
  };

  const isAvatar = shape === 'avatar';

  const renderPreview = () => {
    if (!value) return null;

    const wrapClass = `img-upload__preview-wrap${isAvatar ? ' img-upload__preview-wrap--avatar' : ''}`;
    const imgClass  = isAvatar ? 'img-upload__img--avatar' : 'img-upload__img';

    const overlay = (
      <div className="img-upload__overlay">
        <button className="btn btn--ghost img-upload__overlay-btn" onClick={() => inputRef.current?.click()}>
          Replace
        </button>
        <button className="btn btn--ghost img-upload__overlay-btn img-upload__overlay-btn--danger" onClick={() => onChange('')}>
          Remove
        </button>
      </div>
    );

    if (isAbsoluteSrc(value)) {
      // base64 or full URL — render directly
      return (
        <div className={wrapClass}>
          <img
            src={value}
            alt=""
            className={imgClass}
            onError={(e) => { e.target.style.display = 'none'; }}
          />
          {overlay}
        </div>
      );
    }

    // Relative path — can't load cross-domain; show filename as placeholder
    return (
      <div className={wrapClass}>
        <div
          style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center',
            justifyContent: 'center', gap: 'var(--space-1)',
            height: isAvatar ? 56 : 140,
            background: 'var(--bg-surface-2)',
            borderRadius: isAvatar ? '50%' : 'var(--radius-xs)',
          }}
        >
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <rect x="1" y="1" width="14" height="14" rx="2" stroke="currentColor" strokeWidth="1.2"/>
            <path d="M1 10.5l4-4 3 3 2.5-2.5 4.5 4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/>
            <circle cx="11" cy="5.5" r="1.5" fill="currentColor" opacity="0.4"/>
          </svg>
          <span style={{ fontSize: 'var(--fs-caption)', color: 'var(--fg-secondary)', textAlign: 'center', padding: '0 var(--space-2)', wordBreak: 'break-all' }}>
            {basename(value)}
          </span>
        </div>
        {overlay}
      </div>
    );
  };

  return (
    <div className="img-upload">
      {value ? renderPreview() : (
        <button
          type="button"
          className="img-upload__dropzone"
          onClick={() => inputRef.current?.click()}
          disabled={uploading}
        >
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
            <path d="M9 3v9M5 7l4-4 4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
            <path d="M2 14h14" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
          </svg>
          <span>{uploading ? 'Reading…' : (uploadLabel || 'Upload Image')}</span>
        </button>
      )}
      <input
        ref={inputRef}
        type="file"
        accept="image/*"
        style={{ display: 'none' }}
        onChange={handleChange}
      />
    </div>
  );
}

// ─── Multi-image upload (carousel) ───────────────────────────────────────────

function MultiImageUpload({ value = [], onChange }) {
  const [uploading, setUploading] = React.useState(false);
  const inputRef = React.useRef(null);

  const upload = (file) => {
    setUploading(true);
    const reader = new FileReader();
    reader.onload  = (ev) => { onChange([...value, ev.target.result]); setUploading(false); };
    reader.onerror = ()    => setUploading(false);
    reader.readAsDataURL(file);
  };

  const remove = (idx) => onChange(value.filter((_, i) => i !== idx));

  return (
    <div className="multi-img-upload">
      <div className="multi-img-upload__grid">
        {value.map((url, i) => (
          <div key={i} className="multi-img-upload__item">
            {isAbsoluteSrc(url) ? (
              <img src={url} alt="" className="multi-img-upload__thumb" />
            ) : (
              <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100%', height: '100%', fontSize: 9, color: 'var(--fg-tertiary)', padding: 2, textAlign: 'center', wordBreak: 'break-all' }}>
                {basename(url)}
              </span>
            )}
            <button className="multi-img-upload__remove" onClick={() => remove(i)} type="button">
              <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
                <path d="M1 1l8 8M9 1L1 9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
              </svg>
            </button>
          </div>
        ))}
        <button
          type="button"
          className="multi-img-upload__add"
          onClick={() => inputRef.current?.click()}
          disabled={uploading}
          title="Add image"
        >
          {uploading ? '…' : (
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M8 2v12M2 8h12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
            </svg>
          )}
        </button>
      </div>
      <input
        ref={inputRef}
        type="file"
        accept="image/*"
        style={{ display: 'none' }}
        onChange={(e) => { if (e.target.files[0]) upload(e.target.files[0]); e.target.value = ''; }}
      />
    </div>
  );
}
