// Müşteri bazlı Marka Kiti — logo/renkler/fontlar/sosyal hesaplar/notlar/dosyalar/brief geçmişi
const BKIcons = window.Icons;
const { relativeDate: bkRel } = window.PMStore;

const SOCIAL_PLATFORMS = ['Instagram', 'Facebook', 'LinkedIn', 'X / Twitter', 'TikTok', 'YouTube', 'Web Sitesi', 'Diğer'];

function bkUid() { return Math.random().toString(36).slice(2, 10); }
function bkSaveFile(id, dataUrl) { try { localStorage.setItem('nav_att_' + id, dataUrl); } catch (e) {} }
function bkGetFile(id) { try { return localStorage.getItem('nav_att_' + id); } catch (e) { return null; } }
function bkDelFile(id) { try { localStorage.removeItem('nav_att_' + id); } catch (e) {} }
function bkFmtSize(bytes) {
  if (!bytes) return '';
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return Math.round(bytes / 1024) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}

function BrandKitModal({ project, onUpdateBrandKit, onAddFile, onRemoveFile, onClose }) {
  const bk = project.brandKit || { colors: [], fonts: [], socials: [], notes: '', files: [] };
  const [newColor,  setNewColor]  = React.useState('#ff601f');
  const [newFont,   setNewFont]   = React.useState('');
  const [socPlat,   setSocPlat]   = React.useState(SOCIAL_PLATFORMS[0]);
  const [socHandle, setSocHandle] = React.useState('');
  const [notes,     setNotes]     = React.useState(bk.notes || '');
  const [dragOver,  setDragOver]  = React.useState(false);
  const notesTimer = React.useRef(null);

  const patch = (p) => onUpdateBrandKit(project.id, p);

  const addColor = () => {
    if (!newColor) return;
    patch({ colors: [...(bk.colors || []), newColor] });
  };
  const removeColor = (i) => patch({ colors: (bk.colors || []).filter((_, idx) => idx !== i) });

  const addFont = () => {
    const v = newFont.trim(); if (!v) return;
    patch({ fonts: [...(bk.fonts || []), v] });
    setNewFont('');
  };
  const removeFont = (i) => patch({ fonts: (bk.fonts || []).filter((_, idx) => idx !== i) });

  const addSocial = () => {
    const v = socHandle.trim(); if (!v) return;
    patch({ socials: [...(bk.socials || []), { platform: socPlat, handle: v }] });
    setSocHandle('');
  };
  const removeSocial = (i) => patch({ socials: (bk.socials || []).filter((_, idx) => idx !== i) });

  const onNotesChange = (v) => {
    setNotes(v);
    clearTimeout(notesTimer.current);
    notesTimer.current = setTimeout(() => patch({ notes: v }), 500);
  };

  const handleFiles = (files) => {
    Array.from(files).forEach(file => {
      if (file.size > 4 * 1024 * 1024) { alert(`"${file.name}" 4MB sınırını aşıyor.`); return; }
      const id = bkUid();
      const reader = new FileReader();
      reader.onload = (e) => {
        bkSaveFile(id, e.target.result);
        onAddFile(project.id, { id, name: file.name, type: file.type, size: file.size });
      };
      reader.readAsDataURL(file);
    });
  };
  const removeFile = (fileId) => { bkDelFile(fileId); onRemoveFile(project.id, fileId); };

  const briefHistory = project.briefHistory || [];

  return (
    <div className="confirm-overlay" onClick={onClose}>
      <div className="members-modal brandkit-modal" onClick={e => e.stopPropagation()}>
        <div className="members-modal-header">
          <div className="brandkit-modal-icon" style={{ background: (project.color || 'var(--accent)') + '22', color: project.color || 'var(--accent)' }}>
            <BKIcons.Palette size={18} />
          </div>
          <div>
            <div className="members-modal-title">Marka Kiti</div>
            <div className="members-modal-sub">{project.name}</div>
          </div>
          <button className="icon-btn" style={{ marginLeft: 'auto' }} onClick={onClose}>
            <BKIcons.X size={16} />
          </button>
        </div>

        <div className="members-modal-body">
          {/* Renkler */}
          <div className="members-section-label">Marka Renkleri</div>
          <div className="bk-color-row">
            {(bk.colors || []).map((c, i) => (
              <div key={i} className="bk-color-chip" title={c}>
                <span className="bk-color-swatch" style={{ background: c }} />
                <span className="bk-color-hex">{c}</span>
                <button onClick={() => removeColor(i)}><BKIcons.X size={11} /></button>
              </div>
            ))}
            {!(bk.colors || []).length && <span className="bk-empty-hint">Henüz renk eklenmedi.</span>}
          </div>
          <div className="bk-add-row">
            <input type="color" value={newColor} onChange={e => setNewColor(e.target.value)} className="bk-color-input" />
            <button className="btn btn-ghost btn-sm" onClick={addColor}><BKIcons.Plus size={13} /> Renk Ekle</button>
          </div>

          {/* Fontlar */}
          <div className="members-section-label" style={{ marginTop: 20 }}>Fontlar</div>
          <div className="bk-tag-row">
            {(bk.fonts || []).map((f, i) => (
              <div key={i} className="bk-tag-chip">
                <span style={{ fontFamily: f }}>{f}</span>
                <button onClick={() => removeFont(i)}><BKIcons.X size={11} /></button>
              </div>
            ))}
            {!(bk.fonts || []).length && <span className="bk-empty-hint">Henüz font eklenmedi.</span>}
          </div>
          <div className="bk-add-row">
            <input
              className="f-input" placeholder="Font adı (örn. Bricolage Grotesque)"
              value={newFont} onChange={e => setNewFont(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && addFont()}
            />
            <button className="btn btn-ghost btn-sm" onClick={addFont}><BKIcons.Plus size={13} /> Ekle</button>
          </div>

          {/* Sosyal medya */}
          <div className="members-section-label" style={{ marginTop: 20 }}>Sosyal Medya Hesapları</div>
          <div className="bk-social-list">
            {(bk.socials || []).map((s, i) => (
              <div key={i} className="bk-social-row">
                <span className="bk-social-platform">{s.platform}</span>
                <span className="bk-social-handle">{s.handle}</span>
                <button onClick={() => removeSocial(i)}><BKIcons.X size={12} /></button>
              </div>
            ))}
            {!(bk.socials || []).length && <span className="bk-empty-hint">Henüz hesap eklenmedi.</span>}
          </div>
          <div className="bk-add-row">
            <select className="share-opt-select" value={socPlat} onChange={e => setSocPlat(e.target.value)}>
              {SOCIAL_PLATFORMS.map(p => <option key={p} value={p}>{p}</option>)}
            </select>
            <input
              className="f-input" placeholder="Kullanıcı adı / bağlantı"
              value={socHandle} onChange={e => setSocHandle(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && addSocial()}
            />
            <button className="btn btn-ghost btn-sm" onClick={addSocial}><BKIcons.Plus size={13} /> Ekle</button>
          </div>

          {/* Notlar */}
          <div className="members-section-label" style={{ marginTop: 20 }}>Marka Notları</div>
          <textarea
            className="f-area" rows={3}
            placeholder="Ton, marka kişiliği, kaçınılması gerekenler…"
            value={notes} onChange={e => onNotesChange(e.target.value)}
          />

          {/* Dosyalar */}
          <div className="members-section-label" style={{ marginTop: 20 }}>Dosyalar</div>
          <div
            className={`bk-dropzone${dragOver ? ' drag' : ''}`}
            onDragOver={e => { e.preventDefault(); setDragOver(true); }}
            onDragLeave={() => setDragOver(false)}
            onDrop={e => { e.preventDefault(); setDragOver(false); handleFiles(e.dataTransfer.files); }}
            onClick={() => document.getElementById('bk-file-input').click()}
          >
            <BKIcons.Upload size={16} />
            <span>Logo, marka kılavuzu vb. dosyaları sürükleyin veya tıklayın</span>
            <input id="bk-file-input" type="file" multiple hidden onChange={e => handleFiles(e.target.files)} />
          </div>
          {(bk.files || []).length > 0 && (
            <div className="bk-file-list">
              {(bk.files || []).map(f => (
                <div key={f.id} className="bk-file-row">
                  <BKIcons.FileText size={14} />
                  <span className="bk-file-name">{f.name}</span>
                  <span className="bk-file-size">{bkFmtSize(f.size)}</span>
                  <a href={bkGetFile(f.id) || '#'} download={f.name} className="icon-btn" title="İndir"><BKIcons.Download size={13} /></a>
                  <button className="icon-btn" onClick={() => removeFile(f.id)} title="Sil"><BKIcons.Trash size={13} /></button>
                </div>
              ))}
            </div>
          )}

          {/* Brief geçmişi */}
          {briefHistory.length > 0 && (
            <>
              <div className="members-section-label" style={{ marginTop: 20 }}>Brief Geçmişi</div>
              <div className="bk-history-list">
                {[...briefHistory].reverse().map((h, i) => (
                  <div key={i} className="bk-history-item">
                    <div className="bk-history-date">{bkRel ? bkRel(h.at) : new Date(h.at).toLocaleDateString('tr-TR')}</div>
                    <div className="bk-history-text">{h.text || <em>(boş)</em>}</div>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

window.BrandKitModal = BrandKitModal;
