/* eslint-disable */
// content-store.jsx
// localStorage-backed canonical content for the site.
// Site pages read from Store.* with hardcoded fallbacks; admin pages write here.

const STORE_VERSION = 1;
const STORE_KEYS = {
  projects: 'c1.projects.v1',
  articles: 'c1.articles.v1',
  meta:     'c1.meta.v1',
};

// ── Default project + article shapes (used when promoting hardcoded → store)

const DEFAULT_PROJECT_BODY = {
  subtitle: '',
  role: '',
  location: '',
  brief: '',
  approach: '',
  textBoxes: [
    { label: 'Brief', body: '' },
    { label: 'Direction', body: '' },
    { label: 'Type', body: '' },
    { label: 'Outcome', body: '' },
  ],
  credits: [
    ['Creative Direction', 'Chapter 1'],
    ['Design', 'Studio Team'],
  ],
};

function projectFromWork(w) {
  return {
    id: w.n,
    n: w.n,
    client: w.client || '',
    kind: w.kind || '',
    year: w.year || '',
    tagline: w.tagline || '',
    tags: w.tags || w.services || [],
    palette: w.palette || ['#1a1410', '#991539', '#f0ebe2', '#3a0e1c'],
    featured: !!w.featured,
    ...DEFAULT_PROJECT_BODY,
    subtitle: w.tagline || '',
    role: (w.tags || w.services || []).join(' · '),
    location: (w.kind || '').split(' · ')[1] || '',
  };
}

function articleFromPost(p) {
  const slugify = window.slugify || ((s) => (s || '').toLowerCase().replace(/[^a-z0-9]+/g, '-'));
  return {
    id: slugify(p.title),
    slug: slugify(p.title),
    title: p.title || '',
    dek: p.dek || '',
    cat: p.cat || 'Essay',
    kicker: p.kicker || '',
    byline: p.byline || 'The Studio',
    date: p.date || '',
    palette: p.palette || ['#0e1820', '#3a6a8a', '#d8e8f0', '#1a3050'],
    template: 'normal',
    body: [],
    quote: { text: '', cite: '' },
    photos: [],
    featured: false,
  };
}

// ── Storage primitives ────────────────────────────────────────

function readJSON(key, fallback) {
  try {
    const raw = localStorage.getItem(key);
    if (!raw) return fallback;
    return JSON.parse(raw);
  } catch (e) {
    console.warn('content-store: failed to parse', key, e);
    return fallback;
  }
}

function writeJSON(key, value) {
  try {
    localStorage.setItem(key, JSON.stringify(value));
    return true;
  } catch (e) {
    console.warn('content-store: failed to write', key, e);
    return false;
  }
}

// ── Defaults (built once from hardcoded data on the page) ─────

function defaultProjects() {
  // Prefer WORK_INDEX (richer) when present, else fall back to WORK
  const src = window.WORK_INDEX || window.WORK || [];
  return src.map(projectFromWork);
}

function defaultArticles() {
  const src = window.ALL_POSTS || window.JOURNAL || [];
  return src.map(articleFromPost);
}

// ── Public API ────────────────────────────────────────────────

const Store = {
  // Projects
  getProjects() {
    const stored = readJSON(STORE_KEYS.projects, null);
    if (stored && Array.isArray(stored)) return stored;
    return defaultProjects();
  },
  setProjects(list) {
    return writeJSON(STORE_KEYS.projects, list || []);
  },
  resetProjects() {
    localStorage.removeItem(STORE_KEYS.projects);
  },
  getProject(id) {
    if (!id) return null;
    const list = Store.getProjects();
    return list.find((p) => p.id === id || p.n === id) || null;
  },
  upsertProject(project) {
    const list = Store.getProjects();
    const i = list.findIndex((p) => p.id === project.id);
    if (i >= 0) list[i] = project; else list.push(project);
    return Store.setProjects(list);
  },
  deleteProject(id) {
    const list = Store.getProjects().filter((p) => p.id !== id);
    return Store.setProjects(list);
  },

  // Articles
  getArticles() {
    const stored = readJSON(STORE_KEYS.articles, null);
    if (stored && Array.isArray(stored)) return stored;
    return defaultArticles();
  },
  setArticles(list) {
    return writeJSON(STORE_KEYS.articles, list || []);
  },
  resetArticles() {
    localStorage.removeItem(STORE_KEYS.articles);
  },
  getArticle(id) {
    if (!id) return null;
    const list = Store.getArticles();
    return list.find((a) => a.id === id || a.slug === id) || null;
  },
  upsertArticle(article) {
    const list = Store.getArticles();
    const i = list.findIndex((a) => a.id === article.id);
    if (i >= 0) list[i] = article; else list.push(article);
    return Store.setArticles(list);
  },
  deleteArticle(id) {
    const list = Store.getArticles().filter((a) => a.id !== id);
    return Store.setArticles(list);
  },

  // Bulk export / import
  exportAll() {
    return {
      version: STORE_VERSION,
      exportedAt: new Date().toISOString(),
      projects: Store.getProjects(),
      articles: Store.getArticles(),
    };
  },
  importAll(payload) {
    if (!payload || typeof payload !== 'object') return false;
    if (Array.isArray(payload.projects)) Store.setProjects(payload.projects);
    if (Array.isArray(payload.articles)) Store.setArticles(payload.articles);
    return true;
  },

  // Helpers exposed for admin UI
  defaults: { projects: defaultProjects, articles: defaultArticles },
  KEYS: STORE_KEYS,
  blankProject() {
    const id = String(Date.now()).slice(-6);
    return {
      id, n: id, client: 'Untitled Project', kind: '', year: String(new Date().getFullYear()),
      tagline: '', tags: [], palette: ['#1a1410', '#991539', '#f0ebe2', '#3a0e1c'],
      featured: false, ...DEFAULT_PROJECT_BODY, subtitle: '', role: '', location: '',
    };
  },
  blankArticle() {
    const id = 'untitled-' + String(Date.now()).slice(-6);
    return {
      id, slug: id, title: 'Untitled Article', dek: '',
      cat: 'Essay', kicker: '', byline: 'The Studio', date: '',
      palette: ['#0e1820', '#3a6a8a', '#d8e8f0', '#1a3050'],
      template: 'normal', body: [''], quote: { text: '', cite: '' },
      photos: [], featured: false,
    };
  },
};

// ── Bridge: project Store data back onto the globals the site reads ──
//
// The site components capture local consts (WORK, WORK_INDEX, ALL_POSTS, etc.)
// that are also assigned to window. Mutating the underlying array in place
// keeps both refs in sync. We only override when the user has actually
// stored content (i.e. localStorage has the key) — otherwise the site
// shows the original demo content unchanged.

function _replaceArr(arr, items) {
  if (!Array.isArray(arr) || !Array.isArray(items)) return;
  arr.length = 0;
  for (const x of items) arr.push(x);
}

function _replaceObj(target, source) {
  if (!target || !source) return;
  for (const k of Object.keys(target)) delete target[k];
  Object.assign(target, source);
}

function _projectToWork(p) {
  return {
    n: p.n || p.id,
    client: p.client,
    kind: p.kind,
    year: p.year,
    tagline: p.tagline,
    tags: p.tags || [],
    palette: p.palette,
  };
}

function _projectToWorkIndex(p) {
  return {
    n: p.n || p.id,
    client: p.client,
    kind: p.kind,
    year: p.year,
    services: p.tags || [],
    featured: !!p.featured,
    palette: p.palette,
  };
}

function _articleToPost(a) {
  return {
    cat: a.cat || 'Essay',
    kicker: a.kicker || '',
    title: a.title || '',
    dek: a.dek || '',
    byline: a.byline || '',
    date: a.date || '',
    palette: a.palette || ['#0e1820', '#3a6a8a', '#d8e8f0', '#1a3050'],
  };
}

Store.applyToGlobals = function applyToGlobals() {
  const hasProjects = !!localStorage.getItem(STORE_KEYS.projects);
  const hasArticles = !!localStorage.getItem(STORE_KEYS.articles);

  if (hasProjects) {
    const list = Store.getProjects();
    if (Array.isArray(window.WORK)) _replaceArr(window.WORK, list.map(_projectToWork));
    if (Array.isArray(window.WORK_INDEX)) _replaceArr(window.WORK_INDEX, list.map(_projectToWorkIndex));
  }

  if (hasArticles) {
    const list = Store.getArticles();
    const posts = list.map(_articleToPost);
    if (Array.isArray(window.ALL_POSTS)) _replaceArr(window.ALL_POSTS, posts);
    if (Array.isArray(window.PLAYBOOK)) _replaceArr(window.PLAYBOOK, posts.filter((p) => p.cat === 'The Playbook'));
    if (Array.isArray(window.SCROLL_CULTURE)) _replaceArr(window.SCROLL_CULTURE, posts.filter((p) => p.cat === 'Scroll Culture'));
    if (Array.isArray(window.READING_ROOM)) _replaceArr(window.READING_ROOM, posts.filter((p) => p.cat === 'The Reading Room'));

    // Cover story → first featured, else first article
    const coverArticle = list.find((a) => a.featured) || list[0];
    if (window.MAIN_CHARACTER && coverArticle) {
      _replaceObj(window.MAIN_CHARACTER, _articleToPost(coverArticle));
    }

    // Home page small list (4 most recent)
    if (Array.isArray(window.JOURNAL)) {
      const small = posts.slice(0, 4).map((p) => ({ cat: p.cat, title: p.title, read: '5 min', date: p.date }));
      _replaceArr(window.JOURNAL, small);
    }
  }
};

// Apply now so consumers that capture references on the next tick see
// the projected data. Wrapped in try/catch so a Store bug can never
// blank-screen the public site.
try {
  Store.applyToGlobals();
} catch (err) {
  console.warn('[content-store] applyToGlobals failed; site will use hardcoded defaults', err);
}

window.Store = Store;
