/* global React */
// FirstTakes marketing — shared real-photo controls.
// One module powers app-store / google-play / website. Load AFTER tweaks-panel.jsx
// and BEFORE the page's inline app script. The page's top-level component calls
// `const { panel } = window.useMarketingMedia();` and renders {panel}; that ties the
// media state to the component that draws the phones, so taps/uploads re-render them.
//
// Photos live in localStorage (shared across all three surfaces — upload once), NOT
// in the tweak block, so the source files stay small.

const LS_TILES = "ftm_tiles", LS_REC = "ftm_record", LS_ASSIGN = "ftm_assign", LS_SIG = "ftm_sig";
const DEFAULT_SPORTS = "Show off your favorite snack!";

// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
//  \ud83d\udc47  PICK YOUR PHOTOS HERE \u2014 this is the only block you need to edit.
//
//  These are the photos shown inside the phone mockups across the whole site.
//  Each entry is just a link. It can be either:
//    \u2022 a local file in this repo, e.g.  "assets/photos/basketball.jpeg"
//      (drop new files into assets/photos/ and reference them the same way)
//    \u2022 a full web URL,            e.g.  "https://images.unsplash.com/photo-123\u2026"
//
//  GRID_PHOTOS \u2192 the take thumbnails (friends' feed + your profile archive).
//                Add as many as you like; they cycle through the tiles.
//  RECORD_PHOTO \u2192 the single still shown on the "recording" screen.
//
//  Save the file and reload the page to see your changes.
// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
const GRID_PHOTOS = [
  "assets/photos/lemon-bar.jpeg",
  "assets/photos/strawberries.jpeg",
  "assets/photos/basketball.jpeg",
  "assets/photos/basketball-game.jpeg",
  "assets/photos/dog-pool.jpeg",
  "assets/photos/cow.jpeg",
  "assets/photos/lavender.jpeg",
];
const RECORD_PHOTO = "assets/photos/basketball.jpeg";

const DEFAULT_TILES = GRID_PHOTOS;
const DEFAULT_REC = RECORD_PHOTO;

// Default photo-to-tile map. Feed swaps the 2nd & 3rd take; the archive top row
// pulls varied indices so it isn't all one colour. Tap any tile to override.
const FEED_ORDER = [0, 2, 1];
const ARCH_ORDER = [5, 3, 7, 4, 6, 1];
const ALL_SLOTS = ["feed:0", "feed:1", "feed:2", "archive:0", "archive:1", "archive:2", "archive:3", "archive:4", "archive:5"];

const loadLS = (k) => { try { return JSON.parse(localStorage.getItem(k) || "null"); } catch (e) { return null; } };
const saveLS = (k, v) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) {} };

// The Tweaks panel caches photos in localStorage. When the links above change,
// that cache is stale — so we fingerprint the list and reset the cache whenever
// the fingerprint differs. Net effect: edit the list, reload, see your photos.
const CONFIG_SIG = JSON.stringify(["v2-fixed-order", GRID_PHOTOS, RECORD_PHOTO]);
if (loadLS(LS_SIG) !== CONFIG_SIG) {
  saveLS(LS_TILES, DEFAULT_TILES);
  saveLS(LS_REC, DEFAULT_REC);
  saveLS(LS_ASSIGN, {});
  saveLS(LS_SIG, CONFIG_SIG);
}

// Downscale on import so thumbnails stay small in localStorage.
function downscale(file, max = 760) {
  return new Promise((res) => {
    const img = new Image();
    img.onload = () => {
      const s = Math.min(1, max / Math.max(img.width, img.height));
      const w = Math.round(img.width * s), h = Math.round(img.height * s);
      const c = document.createElement("canvas"); c.width = w; c.height = h;
      c.getContext("2d").drawImage(img, 0, 0, w, h);
      res(c.toDataURL("image/jpeg", 0.82));
    };
    img.onerror = () => res(null);
    const fr = new FileReader();
    fr.onload = () => { img.src = fr.result; };
    fr.onerror = () => res(null);
    fr.readAsDataURL(file);
  });
}

function PhotoButton({ label, multiple, onPick }) {
  const ref = React.useRef(null);
  return (
    <div className="twk-row">
      <div className="twk-lbl"><span>{label}</span></div>
      <input ref={ref} type="file" accept="image/*" multiple={multiple} style={{ display: "none" }}
        onChange={async (e) => { const files = [...e.target.files]; e.target.value = ""; if (!files.length) return; const urls = (await Promise.all(files.map((f) => downscale(f)))).filter(Boolean); onPick(urls); }} />
      <button type="button" className="twk-btn secondary" onClick={() => ref.current.click()}>{multiple ? "Choose images\u2026" : "Choose image\u2026"}</button>
    </div>
  );
}

// Call from the page's top-level component. Sets window.FTMedia (read by the shared
// screens) and returns the Tweaks panel to render.
function useMarketingMedia() {
  const { useTweaks, TweaksPanel, TweakSection, TweakToggle, TweakSelect, TweakButton, TweakText } = window;

  const [t, setTweak] = useTweaks({ showPhotos: true, fit: "cover", grayscale: false, prompt: DEFAULT_SPORTS });
  const [tiles, setTiles] = React.useState(() => loadLS(LS_TILES) || DEFAULT_TILES);
  const [rec, setRec] = React.useState(() => loadLS(LS_REC) || DEFAULT_REC);
  const [assign, setAssign] = React.useState(() => loadLS(LS_ASSIGN) || {});

  const addTiles = (urls) => { const next = [...tiles, ...urls].slice(-8); setTiles(next); saveLS(LS_TILES, next); };
  const clearTiles = () => { setTiles([]); saveLS(LS_TILES, []); };
  const setRecPhoto = (urls) => { const u = urls[0] || null; setRec(u); saveLS(LS_REC, u); };
  const clearRec = () => { setRec(null); saveLS(LS_REC, null); };
  const putAssign = (slot, val) => { const next = { ...assign, [slot]: val }; setAssign(next); saveLS(LS_ASSIGN, next); };
  const resetArrange = () => { setAssign({}); saveLS(LS_ASSIGN, {}); };
  const shuffle = () => {
    if (!tiles.length) return;
    const pool = [...Array(tiles.length).keys()];
    for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; }
    const next = {}; ALL_SLOTS.forEach((s, k) => { next[s] = pool[k % pool.length]; });
    setAssign(next); saveLS(LS_ASSIGN, next);
  };

  // Shared screens (MediaTile / RecordStill / ChallengeCard) read this at render time.
  window.FTMedia = {
    enabled: !!t.showPhotos,
    fit: t.fit,
    bw: !!t.grayscale,
    prompt: t.prompt || DEFAULT_SPORTS,
    tiles,
    record: rec,
    assign,
    _def(slot) {
      const parts = String(slot || "").split(":");
      const i = parseInt(parts[1] || "0", 10) || 0;
      const order = parts[0] === "archive" ? ARCH_ORDER : FEED_ORDER;
      return order[i] != null ? order[i] : i;
    },
    resolveTile(slot) {
      if (!this.enabled || !this.tiles.length) return null;
      const a = this.assign ? this.assign[slot] : null;
      const idx = a != null ? a : this._def(slot);
      return this.tiles[idx % this.tiles.length];
    },
    cycle(slot) {
      if (!this.tiles.length) return;
      const a = this.assign ? this.assign[slot] : null;
      const cur = a != null ? a : this._def(slot);
      putAssign(slot, (cur + 1) % this.tiles.length);
    },
  };

  const panel = (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Photos" />
      <TweakToggle label="Show real photos" value={t.showPhotos} onChange={(v) => setTweak("showPhotos", v)} />
      <PhotoButton label={"Thumbnail photos" + (tiles.length ? " \u00b7 " + tiles.length : "")} multiple onPick={addTiles} />
      <PhotoButton label={"Record screen photo" + (rec ? " \u00b7 1" : "")} onPick={setRecPhoto} />
      <div style={{ display: "flex", gap: 6 }}>
        <TweakButton label="Clear thumbs" secondary onClick={clearTiles} />
        <TweakButton label="Clear record" secondary onClick={clearRec} />
      </div>
      <TweakSection label="Arrange" />
      <div style={{ color: "rgba(41,38,27,.62)", lineHeight: 1.45 }}>Tap any thumbnail on a screen to swap which photo it shows.</div>
      <div style={{ display: "flex", gap: 6 }}>
        <TweakButton label="Shuffle" secondary onClick={shuffle} />
        <TweakButton label="Reset" secondary onClick={resetArrange} />
      </div>
      <TweakSection label="Challenge" />
      <TweakText label="Prompt" value={t.prompt} onChange={(v) => setTweak("prompt", v)} />
      <TweakSection label="Treatment" />
      <TweakSelect label="Photo fit" value={t.fit} options={[{ value: "cover", label: "Fill (cover)" }, { value: "contain", label: "Fit (contain)" }]} onChange={(v) => setTweak("fit", v)} />
      <TweakToggle label="Black & white" value={t.grayscale} onChange={(v) => setTweak("grayscale", v)} />
    </TweaksPanel>
  );

  return { panel };
}

Object.assign(window, { useMarketingMedia, PhotoButton, downscale });
