/* eslint-disable */
// Memory Wall — timeline of memory cards with contributor pills and photo placeholders

const SEED_MEMORIES = [
  { id: 1, title: "Goa sunset, family trip", date: "Apr 14, 2026", contributor: "Priya", description: "Our last evening on Palolem beach. Pakoras and cold coffee. The kids drew names in the sand.", tags: ["vacation", "family", "beach"], photo: "linear-gradient(135deg, #F97316 0%, #DB2777 50%, #4F46E5 100%)" },
  { id: 2, title: "Arjun's school play",     date: "Mar 22, 2026", contributor: "Mom",   description: "He played the lead. Three weeks of rehearsals paid off — not a single line missed.", tags: ["milestone", "school"], photo: "linear-gradient(135deg, #9333EA 0%, #3B82F6 100%)" },
  { id: 3, title: "Nani's 80th birthday",    date: "Feb 02, 2026", contributor: "Dad",   description: "Three generations under one roof. Mom made the cake from scratch — the recipe Nani taught her.", tags: ["birthday", "family", "milestone"], photo: "linear-gradient(135deg, #EC4899 0%, #F59E0B 100%)" },
  { id: 4, title: "First snow of the year",  date: "Jan 11, 2026", contributor: "Arjun", description: "Priya saw it first from the window and woke everyone up at 6am.", tags: ["winter"], photo: null },
];

const MemoryRow = ({ memory, isLast, onDelete, onEdit }) => (
  <div className="relative">
    {!isLast && (
      <div className="absolute left-4 top-12 bottom-[-20px] w-0.5 bg-blue-200 dark:bg-blue-800 hidden md:block"></div>
    )}
    <div className="absolute left-0 top-3 w-8 h-8 bg-blue-500 rounded-full border-4 border-gray-50 dark:border-gray-900 z-10 flex items-center justify-center text-white text-sm">
      📷
    </div>
    <div className="ml-12 md:ml-14">
      <Card>
        <div className="flex justify-between items-start mb-3 gap-3 flex-wrap">
          <div>
            <p className="text-xs text-gray-500 dark:text-gray-400 font-semibold uppercase tracking-wide">{memory.date}</p>
            <h3 className="text-xl font-bold text-gray-900 dark:text-white mt-1">{memory.title}</h3>
          </div>
          <Pill tone="info">{memory.contributor}</Pill>
        </div>
        {(memory.photos && memory.photos.length > 0) ? (
          <div className="mb-4 grid gap-2" style={{ gridTemplateColumns: memory.photos.length === 1 ? "1fr" : "repeat(auto-fill, minmax(150px, 1fr))" }}>
            {memory.photos.map((src, i) => (
              <img key={i} src={src} alt={memory.title + " " + (i+1)} className="rounded-lg w-full h-44 object-cover" />
            ))}
          </div>
        ) : memory.photo && !memory.photo.startsWith("linear") ? (
          <div className="mb-4">
            <img src={memory.photo} alt={memory.title} className="rounded-lg w-full h-44 object-cover" />
          </div>
        ) : null}
        <p className="text-gray-700 dark:text-gray-300 mb-3">{memory.description}</p>
        <div className="flex gap-2 flex-wrap mb-3">
          {(Array.isArray(memory.tags) ? memory.tags : []).map((t) => <ChipSq key={t} tone="purple">{t}</ChipSq>)}
        </div>
        <div className="flex gap-3 text-sm">
          <button onClick={() => onEdit(memory)} className="text-blue-600 dark:text-blue-400 hover:underline">Edit</button>
          <button onClick={() => onDelete(memory.id)} className="text-red-600 dark:text-red-400 hover:underline">Delete</button>
        </div>
      </Card>
    </div>
  </div>
);

const MemoryWallScreen = () => {
  const [memories, setMemories] = React.useState(() => {
    const stored = Storage.getArray('familyhub_memories', 'memories');
    return stored;
  });
  const saveMemories = (newMems) => { setMemories(newMems); Storage.set('familyhub_memories', { memories: newMems }); };
  const [showAdd, setShowAdd] = React.useState(false);
  const [draft, setDraft] = React.useState({ title: "", date: "", contributor: "", description: "", tags: "" });
  const [photoFiles, setPhotoFiles] = React.useState([]);
  const addMemory = () => {
    if (!draft.title.trim()) return;
    const finish = (photos) => {
      const newMem = { id: Date.now(), title: draft.title, date: draft.date || new Date().toLocaleDateString('en-US', {year:'numeric',month:'short',day:'numeric'}), contributor: draft.contributor || "You", description: draft.description, tags: draft.tags.split(',').map(t=>t.trim()).filter(Boolean), photos: photos, photo: photos.length ? photos[0] : null };
      saveMemories([newMem, ...memories]);
      setDraft({ title: "", date: "", contributor: "", description: "", tags: "" });
      setPhotoFiles([]);
      setShowAdd(false);
    };
    if (photoFiles.length > 0) {
      const photos = [];
      let loaded = 0;
      Array.from(photoFiles).forEach(file => {
        const reader = new FileReader();
        reader.onload = (e) => { photos.push(e.target.result); loaded++; if (loaded === photoFiles.length) finish(photos); };
        reader.readAsDataURL(file);
      });
    } else { finish([]); }
  };
  const deleteMemory = (id) => { if (!window.confirm("Are you sure you want to delete this memory?")) return; saveMemories(memories.filter(m => m.id !== id)); };
  const [editMem, setEditMem] = React.useState(null);
  const startEditMem = (m) => { setEditMem({ ...m, tags: Array.isArray(m.tags) ? m.tags.join(', ') : (m.tags || '') }); };
  const saveEditMem = () => {
    if (!editMem.title.trim()) return;
    saveMemories(memories.map(m => m.id === editMem.id ? { ...m, title: editMem.title.trim(), date: editMem.date || m.date, contributor: editMem.contributor || m.contributor, description: editMem.description, tags: editMem.tags ? editMem.tags.split(',').map(t => t.trim()).filter(Boolean) : [] } : m));
    setEditMem(null);
  };

  return (
  <section className="p-4 md:p-6">
    <div className="flex justify-between items-center mb-6">
      <h2 className="text-3xl font-bold text-gray-900 dark:text-white">Memory Wall</h2>
      <BtnPrimary onClick={() => setShowAdd(true)}>+ Add Memory</BtnPrimary>
    </div>
    {showAdd && (
      <Modal title="Add Memory" onClose={() => setShowAdd(false)} onSubmit={addMemory} submitLabel="Add Memory">
        <div className="space-y-4">
          <div><Label required>Title</Label><Input placeholder="e.g. Goa sunset, family trip" value={draft.title} onChange={e => setDraft({...draft, title: e.target.value})} autoFocus /></div>
          <div><Label>Date</Label><Input type="date" value={draft.date} onChange={e => setDraft({...draft, date: e.target.value})} /></div>
          <div><Label>Added by</Label><Input placeholder="Your name" value={draft.contributor} onChange={e => setDraft({...draft, contributor: e.target.value})} /></div>
          <div><Label>Description</Label><Textarea rows={3} placeholder="Tell the story..." value={draft.description} onChange={e => setDraft({...draft, description: e.target.value})} /></div>
          <div><Label>Tags (comma separated)</Label><Input placeholder="vacation, family, beach" value={draft.tags} onChange={e => setDraft({...draft, tags: e.target.value})} /></div>
          <div>
            <Label>Photos</Label>
            <input type="file" accept="image/*" multiple onChange={e => setPhotoFiles(e.target.files)} className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 text-sm" />
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">Select one or more photos to attach.</p>
          </div>
        </div>
      </Modal>
    )}
    {editMem && (
      <Modal title="Edit Memory" onClose={() => setEditMem(null)} onSubmit={saveEditMem} submitLabel="Save">
        <div className="space-y-4">
          <div><Label required>Title</Label><Input value={editMem.title} onChange={e => setEditMem({...editMem, title: e.target.value})} autoFocus /></div>
          <div><Label>Date</Label><Input type="date" value={editMem.date || ''} onChange={e => setEditMem({...editMem, date: e.target.value})} /></div>
          <div><Label>Added by</Label><Input value={editMem.contributor || ''} onChange={e => setEditMem({...editMem, contributor: e.target.value})} /></div>
          <div><Label>Description</Label><Textarea rows={3} value={editMem.description || ''} onChange={e => setEditMem({...editMem, description: e.target.value})} /></div>
          <div><Label>Tags (comma separated)</Label><Input value={editMem.tags} onChange={e => setEditMem({...editMem, tags: e.target.value})} /></div>
        </div>
      </Modal>
    )}
    <div className="space-y-8">
      {memories.map((m, i) => (
        <MemoryRow key={m.id} memory={m} isLast={i === memories.length - 1} onDelete={deleteMemory} onEdit={startEditMem} />
      ))}
    </div>
  </section>
  );
};

window.MemoryWallScreen = MemoryWallScreen;
