// Vendor profiles — admin-managed list, persisted to localStorage
// Each vendor gets a unique slug used in the URL: ?vendor=slug

const VENDORS_STORAGE_KEY = 'cabinet_intake_vendors_v1';

function slugify(s) {
  return (s || '').toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .slice(0, 40);
}

function makeVendor(name = '') {
  return {
    id: 'v_' + Date.now() + '_' + Math.random().toString(36).slice(2, 7),
    slug: slugify(name) || 'vendor',
    name,
    contact: '',
    phone: '',
    email: '',
    poPrefix: '',
    welcomeMessage: '',
    homeType: '',
  };
}

function loadVendors() {
  try {
    const raw = localStorage.getItem(VENDORS_STORAGE_KEY);
    return raw ? JSON.parse(raw) : [];
  } catch { return []; }
}

function saveVendors(vendors) {
  try { localStorage.setItem(VENDORS_STORAGE_KEY, JSON.stringify(vendors)); } catch {}
}

// Read ?vendor= or ?v= from the URL
function getVendorFromURL() {
  try {
    const params = new URLSearchParams(window.location.search);
    return params.get('vendor') || params.get('v') || null;
  } catch { return null; }
}

// Build the vendor link for the current page
function buildVendorLink(slug) {
  const url = new URL(window.location.href);
  url.search = '';
  url.hash = '';
  url.searchParams.set('vendor', slug);
  return url.toString();
}

// Apply a vendor's defaults to the intake data
function applyVendorToData(data, vendor) {
  if (!vendor) return data;
  return {
    ...data,
    vendorName:    data.vendorName    || vendor.name    || '',
    vendorContact: data.vendorContact || vendor.contact || '',
    vendorPhone:   data.vendorPhone   || vendor.phone   || '',
    vendorEmail:   data.vendorEmail   || vendor.email   || '',
    vendorPO:      data.vendorPO      || (vendor.poPrefix ? vendor.poPrefix : ''),
    homeType:      vendor.homeType      || data.homeType,
    _vendorSlug: vendor.slug,
  };
}

// ============================================================
// Vendors admin tab
// ============================================================
function VendorsAdmin({ vendors, setVendors }) {
  const [editingId, setEditingId] = React.useState(null);
  const [copiedId, setCopiedId] = React.useState(null);

  const addVendor = () => {
    const v = makeVendor('New Vendor');
    const next = [...vendors, v];
    setVendors(next);
    setEditingId(v.id);
  };

  const updateVendor = (id, patch) => {
    setVendors(vendors.map(v => v.id === id ? { ...v, ...patch } : v));
  };

  const removeVendor = (id) => {
    if (!confirm('Remove this vendor profile? Any saved link will stop prefilling.')) return;
    setVendors(vendors.filter(v => v.id !== id));
    if (editingId === id) setEditingId(null);
  };

  const copyLink = async (slug, id) => {
    const link = buildVendorLink(slug);
    try {
      await navigator.clipboard.writeText(link);
      setCopiedId(id);
      setTimeout(() => setCopiedId(null), 1500);
    } catch {
      // Fallback: show prompt
      window.prompt('Copy this link:', link);
    }
  };

  const editing = vendors.find(v => v.id === editingId);

  return (
    <div className="vendors-admin">
      <div className="vendors-list">
        <div className="vendors-list-head">
          <div>
            <div className="t">Vendor profiles</div>
            <div className="s">{vendors.length} configured</div>
          </div>
          <button className="btn primary" onClick={addVendor}>
            <Icon.Plus/> Add vendor
          </button>
        </div>

        {vendors.length === 0 ? (
          <div className="vendors-empty">
            <p>No vendors yet. Add one to generate a custom link they can bookmark.</p>
          </div>
        ) : (
          <div className="vendors-rows">
            {vendors.map(v => (
              <div key={v.id} className={'vendor-row' + (editingId === v.id ? ' editing' : '')}>
                <button className="vendor-row-main" onClick={() => setEditingId(editingId === v.id ? null : v.id)}>
                  <div className="vendor-mark">{(v.name || '?').slice(0, 1).toUpperCase()}</div>
                  <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
                    <div className="n">{v.name || 'Untitled vendor'}</div>
                    <div className="m mono">/{v.slug}</div>
                  </div>
                </button>
                <button className="btn ghost" onClick={() => copyLink(v.slug, v.id)} title="Copy custom link">
                  {copiedId === v.id ? <><Icon.Check/> Copied</> : <><Icon.Link/> Copy link</>}
                </button>
                <button className="btn ghost danger-hover" onClick={() => removeVendor(v.id)} title="Remove">
                  <Icon.Trash/>
                </button>
              </div>
            ))}
          </div>
        )}
      </div>

      {editing && (
        <div className="vendor-edit">
          <div className="vendor-edit-head">
            <h3>Edit · {editing.name || 'Untitled'}</h3>
            <button className="btn ghost" onClick={() => setEditingId(null)}><Icon.X/></button>
          </div>

          <div className="vendor-link-preview">
            <div className="eyebrow">Custom link</div>
            <div className="vendor-link-row">
              <code className="mono">{buildVendorLink(editing.slug)}</code>
              <button className="btn primary" onClick={() => copyLink(editing.slug, editing.id)}>
                {copiedId === editing.id ? <><Icon.Check/> Copied</> : <><Icon.Link/> Copy</>}
              </button>
            </div>
            <div className="hint">Share this link with the vendor. When they open it, the vendor fields are prefilled and they see a portal banner.</div>
          </div>

          <div className="field-grid">
            <div className="field">
              <label>Vendor name <span className="req">*</span></label>
              <input className="input" value={editing.name}
                onChange={e => updateVendor(editing.id, { name: e.target.value, slug: slugify(e.target.value) || editing.slug })}/>
            </div>
            <div className="field">
              <label>URL slug</label>
              <input className="input mono" value={editing.slug}
                onChange={e => updateVendor(editing.id, { slug: slugify(e.target.value) })}/>
              <div className="hint">Auto-generated from name. You can override.</div>
            </div>
            <div className="field">
              <label>Default contact person</label>
              <input className="input" value={editing.contact}
                onChange={e => updateVendor(editing.id, { contact: e.target.value })}
                placeholder="Project manager / point of contact"/>
            </div>
            <div className="field">
              <label>Phone</label>
              <input className="input mono" value={editing.phone}
                onChange={e => updateVendor(editing.id, { phone: e.target.value })}
                placeholder="(480) 555-0100"/>
            </div>
            <div className="field">
              <label>Email</label>
              <input className="input" value={editing.email}
                onChange={e => updateVendor(editing.id, { email: e.target.value })}
                placeholder="pm@vendor.com"/>
            </div>
            <div className="field">
              <label>PO prefix</label>
              <input className="input mono" value={editing.poPrefix}
                onChange={e => updateVendor(editing.id, { poPrefix: e.target.value })}
                placeholder="e.g. SVC-"/>
              <div className="hint">Prefilled at the start of the PO field — vendor types only the number.</div>
            </div>
            <div className="field span-2">
              <label>Welcome banner message <span style={{ fontWeight: 'normal', color: 'var(--ink-faint)' }}>(optional)</span></label>
              <input className="input" value={editing.welcomeMessage}
                onChange={e => updateVendor(editing.id, { welcomeMessage: e.target.value })}
                placeholder='e.g. "Submit a job for our team to repair."'/>
              <div className="hint">Shown above the form when the vendor opens their link.</div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ============================================================
// Vendor portal banner (shown on the intake when a vendor is detected)
// ============================================================
function VendorBanner({ vendor, onSwitchToOpen }) {
  if (!vendor) return null;
  return (
    <div className="vendor-banner no-print">
      <div className="vb-mark">{(vendor.name || '?').slice(0, 1).toUpperCase()}</div>
      <div style={{ flex: 1 }}>
        <div className="vb-eyebrow">Vendor portal</div>
        <div className="vb-name">{vendor.name}</div>
        {vendor.welcomeMessage && <div className="vb-msg">{vendor.welcomeMessage}</div>}
      </div>
      <button className="btn ghost" onClick={onSwitchToOpen} title="Use the open intake form instead">
        Not {vendor.name}?
      </button>
    </div>
  );
}

// Manual vendor-code entry (alternative to URL)
function VendorCodeEntry({ vendors, onPick }) {
  const [code, setCode] = React.useState('');
  const [error, setError] = React.useState('');

  const submit = () => {
    const slug = slugify(code);
    const v = vendors.find(x => x.slug === slug);
    if (!v) { setError('No vendor matches that code.'); return; }
    onPick(v);
  };

  return (
    <div className="vendor-code-entry no-print">
      <div className="eyebrow">Have a vendor code?</div>
      <div style={{ display: 'flex', gap: 8, marginTop: 6 }}>
        <input className="input mono" value={code}
          onChange={e => { setCode(e.target.value); setError(''); }}
          onKeyDown={e => e.key === 'Enter' && submit()}
          placeholder="e.g. sun-valley"/>
        <button className="btn secondary" onClick={submit}>Apply</button>
      </div>
      {error && <div className="hint" style={{ color: 'var(--danger)', marginTop: 4 }}>{error}</div>}
    </div>
  );
}

Object.assign(window, {
  loadVendors, saveVendors, makeVendor, slugify,
  getVendorFromURL, buildVendorLink, applyVendorToData,
  VendorsAdmin, VendorBanner, VendorCodeEntry,
});
