'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { ArrowLeft, ArrowRight, BookHeart, BookOpen, Check, ChevronLeft, ChevronRight, Download, Heart, Home as HomeIcon, Lightbulb, LockKeyhole, Menu, Mic, Pause, Play, Sparkles, Square, X } from 'lucide-react';

type View = 'home' | 'setup' | 'record' | 'library';
type Story = { id:string; prompt:string; chapter:string; note:string; date:string; duration:number; hasAudio:boolean };

const prompts = [
  { chapter:'Beginnings', title:'What is the very first memory you can still picture?', help:'Think about the place, the people nearby, a sound, a smell, or how the light looked.', nudge:'Who else was there? What were they like?' },
  { chapter:'Beginnings', title:'What was the home you grew up in like?', help:'Walk us from room to room, or tell us about your favorite corner.', nudge:'What could you hear from outside?' },
  { chapter:'Family', title:'What is something your parents or grandparents taught you?', help:'It could be practical advice, a tradition, or a lesson you understood years later.', nudge:'Do you remember the exact words they used?' },
  { chapter:'Family', title:'Which family celebration did you look forward to most?', help:'Tell us about the food, rituals, people, and feeling of that day.', nudge:'Who made it feel special?' },
  { chapter:'Becoming', title:'When did you first feel truly grown up?', help:'There may have been a choice, responsibility, journey, or person that changed you.', nudge:'What would your younger self have thought?' },
  { chapter:'Becoming', title:'How did you meet someone who changed your life?', help:'Take your time. Begin with where you were and what you first noticed.', nudge:'What surprised you about them?' },
  { chapter:'Joy', title:'What ordinary moment has brought you lasting joy?', help:'Small memories often become the ones a family treasures most.', nudge:'Why do you think it stayed with you?' },
  { chapter:'Joy', title:'What meal tastes like home to you?', help:'Who made it, when did you eat it, and what made it unforgettable?', nudge:'Could you teach us how to make it?' },
  { chapter:'Wisdom', title:'What difficult season taught you the most?', help:'Share only what feels comfortable. There is no right way to tell it.', nudge:'What helped you keep going?' },
  { chapter:'Wisdom', title:'What do you wish you had worried less about?', help:'Imagine you are speaking to your younger self—or to us.', nudge:'What mattered more in the end?' },
  { chapter:'Legacy', title:'What do you hope our family always remembers?', help:'A value, a story, a person, or a way of caring for one another.', nudge:'How can we carry it forward?' },
  { chapter:'Legacy', title:'What would you like to say to future generations?', help:'Speak as if they are sitting right beside you.', nudge:'What do you hope they feel when they hear your voice?' },
];

const seedStories: Story[] = [
  { id:'sample-1', prompt:'What was the home you grew up in like?', chapter:'Beginnings', note:'The jasmine outside our first home and summer evenings on the front step.', date:'A family favorite', duration:222, hasAudio:false },
  { id:'sample-2', prompt:'What meal tastes like home to you?', chapter:'Joy', note:'Sunday soup, too many cousins at one table, and the recipe nobody wrote down.', date:'Example story', duration:174, hasAudio:false },
];

function formatTime(total:number){ const m=Math.floor(total/60); const s=total%60; return `${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`; }

async function recordingStore(id:string, blob:Blob){
  const request=indexedDB.open('kyuc-memories',1);
  request.onupgradeneeded=()=>request.result.createObjectStore('recordings');
  await new Promise<void>((resolve,reject)=>{ request.onsuccess=()=>resolve(); request.onerror=()=>reject(request.error); });
  const tx=request.result.transaction('recordings','readwrite'); tx.objectStore('recordings').put(blob,id);
  await new Promise<void>((resolve,reject)=>{ tx.oncomplete=()=>resolve(); tx.onerror=()=>reject(tx.error); }); request.result.close();
}

async function recordingLoad(id:string){
  const request=indexedDB.open('kyuc-memories',1);
  await new Promise<void>((resolve,reject)=>{ request.onsuccess=()=>resolve(); request.onerror=()=>reject(request.error); });
  const tx=request.result.transaction('recordings','readonly'); const get=tx.objectStore('recordings').get(id);
  const blob=await new Promise<Blob|undefined>((resolve,reject)=>{ get.onsuccess=()=>resolve(get.result); get.onerror=()=>reject(get.error); }); request.result.close(); return blob;
}

export default function Home(){
  const [view,setView]=useState<View>('home'); const [menu,setMenu]=useState(false); const [storyteller,setStoryteller]=useState(''); const [relationship,setRelationship]=useState('Grandparent');
  const [promptIndex,setPromptIndex]=useState(0); const [note,setNote]=useState(''); const [stories,setStories]=useState<Story[]>(seedStories); const [recording,setRecording]=useState(false);
  const [recorded,setRecorded]=useState<Blob|null>(null); const [seconds,setSeconds]=useState(0); const [permissionError,setPermissionError]=useState(''); const [saved,setSaved]=useState(false); const [playingId,setPlayingId]=useState<string|null>(null);
  const recorder=useRef<MediaRecorder|null>(null); const chunks=useRef<Blob[]>([]); const audio=useRef<HTMLAudioElement|null>(null);

  useEffect(()=>{ const raw=localStorage.getItem('kyuc-stories'); if(raw){ try{ setStories(JSON.parse(raw)); }catch{} } const who=localStorage.getItem('kyuc-storyteller'); if(who)setStoryteller(who); },[]);
  useEffect(()=>{ if(!recording)return; const timer=setInterval(()=>setSeconds(s=>s+1),1000); return()=>clearInterval(timer); },[recording]);
  useEffect(()=>()=>{ if(recorder.current?.state==='recording')recorder.current.stop(); audio.current?.pause(); },[]);

  const completed=stories.filter(s=>!s.id.startsWith('sample')).length; const prompt=prompts[promptIndex]; const chapters=useMemo(()=>Array.from(new Set(prompts.map(p=>p.chapter))),[]);
  function navigate(next:View){ setView(next); setMenu(false); window.scrollTo({top:0,behavior:'smooth'}); }
  function begin(){ navigate(storyteller?'record':'setup'); }
  function finishSetup(){ const clean=storyteller.trim()||'Grandma'; setStoryteller(clean); localStorage.setItem('kyuc-storyteller',clean); navigate('record'); }

  async function toggleRecord(){
    if(recording){ recorder.current?.stop(); setRecording(false); return; }
    setPermissionError(''); setSaved(false); setRecorded(null); setSeconds(0);
    try{ const stream=await navigator.mediaDevices.getUserMedia({audio:true}); chunks.current=[]; const media=new MediaRecorder(stream); recorder.current=media; media.ondataavailable=e=>{if(e.data.size)chunks.current.push(e.data)}; media.onstop=()=>{ const blob=new Blob(chunks.current,{type:media.mimeType||'audio/webm'}); setRecorded(blob); stream.getTracks().forEach(t=>t.stop()); }; media.start(); setRecording(true); }
    catch{ setPermissionError('Microphone access is off. You can enable it in your browser, or save a written note instead.'); }
  }

  async function saveStory(next:boolean){
    const id=`story-${Date.now()}`; const story:Story={id,prompt:prompt.title,chapter:prompt.chapter,note:note.trim(),date:new Date().toLocaleDateString('en-US',{month:'long',day:'numeric',year:'numeric'}),duration:seconds,hasAudio:!!recorded};
    if(recorded)await recordingStore(id,recorded); const updated=[story,...stories]; setStories(updated); localStorage.setItem('kyuc-stories',JSON.stringify(updated)); setSaved(true); setNote(''); setRecorded(null); setSeconds(0);
    if(next&&promptIndex<prompts.length-1)setTimeout(()=>{setPromptIndex(i=>i+1);setSaved(false)},450);
  }

  async function playStory(story:Story){
    if(playingId===story.id){ audio.current?.pause(); setPlayingId(null); return; } audio.current?.pause();
    if(!story.hasAudio){ setPlayingId(story.id); setTimeout(()=>setPlayingId(null),1800); return; }
    const blob=await recordingLoad(story.id); if(!blob)return; const player=new Audio(URL.createObjectURL(blob)); audio.current=player; player.onended=()=>setPlayingId(null); await player.play(); setPlayingId(story.id);
  }

  return <main className="app-shell">
    <header className="site-header">
      <button className="brand brand-button" onClick={()=>navigate('home')} aria-label="Kyuc home"><span className="brand-mark">K</span><span><strong>Kyuc</strong><small>Memories that move through time</small></span></button>
      <nav aria-label="Main navigation" className={menu?'nav-open':''}><button onClick={()=>navigate('home')}><HomeIcon size={16}/> Home</button><button onClick={()=>navigate('library')}><BookHeart size={16}/> My stories <span className="story-count">{completed}</span></button><button className="nav-cta" onClick={begin}><Mic size={16}/> Tell a story</button></nav>
      <button className="menu-button" onClick={()=>setMenu(v=>!v)} aria-label="Open menu">{menu?<X/>:<Menu/>}</button>
    </header>

    {view==='home'&&<>
      <section className="hero" id="top"><div className="hero-copy"><p className="eyebrow">A gift for generations</p><h1>Your voice.<br/><em>Your stories.</em><br/>Always with them.</h1><p className="hero-lede">Kyuc gently guides parents and grandparents through the memories that made them—one easy conversation at a time.</p><div className="hero-actions"><button className="primary-button" onClick={begin}><Mic size={20}/> Tell my first story <ArrowRight size={18}/></button><button className="text-button" onClick={()=>navigate('library')}><Play size={18} fill="currentColor"/> Hear an example</button></div><p className="reassurance"><LockKeyhole size={15}/> Private by design · No typing needed</p></div>
        <div className="memory-card" aria-label="Example saved memory"><div className="photo-frame"><img src="/og.png" alt="Kyuc family memory keepsake"/><span className="tape tape-one"/><span className="tape tape-two"/></div><p className="script-note">“I can still smell the jasmine outside our first home...”</p><div className="audio-line"><button onClick={()=>playStory(seedStories[0])} aria-label="Play example memory">{playingId==='sample-1'?<Pause size={16}/>:<Play size={16} fill="currentColor"/>}</button><div className="wave" aria-hidden="true">{Array.from({length:34}).map((_,i)=><i key={i} style={{height:`${8+((i*13)%22)}px`}}/>)}</div><span>3:42</span></div><div className="memory-meta"><span>Story 01</span><strong>Where it all began</strong><small>Recorded by Grandma Linh</small></div></div></section>
      <section className="steps" id="how"><div><Mic/><strong>Just talk</strong><span>Simple prompts help the stories flow naturally.</span></div><div><Sparkles/><strong>We shape the memory</strong><span>Voice and notes become a beautiful keepsake.</span></div><div><BookOpen/><strong>Share for generations</strong><span>Your family can return to every story, anytime.</span></div></section>
      <section className="origin"><p className="eyebrow">The meaning behind our name</p><h2>Born from <em>Ký Ức</em>—the Vietnamese word for memory.</h2><p>Kyuc is a place for the moments that shape a life and keep moving through a family. Not a perfect biography. Just real voices, honest stories, and the wisdom we never want to lose.</p><button className="primary-button" onClick={begin}>Begin a family keepsake <ArrowRight size={18}/></button></section>
    </>}

    {view==='setup'&&<section className="center-stage setup-stage"><button className="back-link" onClick={()=>navigate('home')}><ArrowLeft size={18}/> Back home</button><div className="setup-card"><div className="soft-icon"><Heart/></div><p className="eyebrow">Before we begin</p><h2>Who is telling this story?</h2><p>This helps Kyuc make every prompt feel personal and warm.</p><label>What should your family call you?<input autoFocus value={storyteller} onChange={e=>setStoryteller(e.target.value)} placeholder="For example: Grandma, Dad, Bà Ngoại" onKeyDown={e=>{if(e.key==='Enter')finishSetup()}}/></label><fieldset><legend>Your place in the family</legend><div className="choice-row">{['Grandparent','Parent','Family friend','Other'].map(item=><button key={item} className={relationship===item?'choice active':'choice'} onClick={()=>setRelationship(item)}>{relationship===item&&<Check size={16}/>} {item}</button>)}</div></fieldset><button className="primary-button wide" onClick={finishSetup}>Start my first chapter <ArrowRight size={19}/></button><p className="tiny"><LockKeyhole size={14}/> Your stories stay on this device unless you choose to share them.</p></div></section>}

    {view==='record'&&<section className="record-shell"><div className="record-top"><button className="back-link" onClick={()=>navigate('library')}><ChevronLeft size={19}/> My stories</button><div><span>Chapter {chapters.indexOf(prompt.chapter)+1} · {prompt.chapter}</span><strong>{promptIndex+1} of {prompts.length}</strong></div></div><div className="progress-track"><i style={{width:`${((promptIndex+1)/prompts.length)*100}%`}}/></div>
      <article className="prompt-card"><p className="eyebrow">Story prompt {String(promptIndex+1).padStart(2,'0')}</p><h2>{prompt.title}</h2><p className="prompt-help">{prompt.help}</p><div className={`recorder-box ${recording?'is-recording':''} ${recorded?'has-recording':''}`}><div className="timer">{formatTime(seconds)}</div><button className="record-button" onClick={toggleRecord} aria-label={recording?'Stop recording':'Start recording'}>{recording?<Square fill="currentColor"/>:<Mic/>}<span>{recording?'Finish recording':recorded?'Record again':'Tap to record'}</span></button>{recording&&<div className="live-wave" aria-hidden="true">{Array.from({length:18}).map((_,i)=><i key={i}/>)}</div>}{recorded&&<p className="recorded-ok"><Check size={18}/> Your memory is ready to save.</p>}{!recording&&!recorded&&<p>You can speak for as long as you like. Pause anytime.</p>}{permissionError&&<p className="error-text">{permissionError}</p>}</div>
      <label className="notes-label">Anything else you want to remember?<span>Optional</span><textarea value={note} onChange={e=>setNote(e.target.value)} placeholder="Add a name, date, place, recipe, or a few words to go with your voice..."/></label><div className="prompt-actions"><button className="secondary-button" disabled={promptIndex===0} onClick={()=>setPromptIndex(i=>Math.max(0,i-1))}><ChevronLeft/> Previous</button><button className="primary-button" disabled={!recorded&&!note.trim()} onClick={()=>saveStory(true)}>{saved?<><Check/> Saved</>:<>Save & next story <ChevronRight/></>}</button></div></article>
      <aside className="gentle-nudge"><Lightbulb/><div><strong>A gentle nudge</strong><p>{prompt.nudge}</p></div></aside></section>}

    {view==='library'&&<section className="library-shell"><div className="library-heading"><div><p className="eyebrow">Your family archive</p><h2>{storyteller?`${storyteller}’s stories`:'Stories live here.'}</h2><p>Every voice note and detail is kept together, ready to revisit.</p></div><button className="primary-button" onClick={begin}><Mic size={19}/> Tell another story</button></div>
      {completed===0&&<div className="welcome-banner"><div className="soft-icon"><Sparkles/></div><div><strong>Your first chapter is waiting.</strong><span>Start with one gentle question. Five minutes is enough.</span></div><button onClick={begin}>Begin <ArrowRight/></button></div>}
      <div className="library-grid">{stories.map((story,index)=><article className={`story-card ${story.id.startsWith('sample')?'sample':''}`} key={story.id}><div className="story-number">{story.id.startsWith('sample')?'Example':String(stories.length-index).padStart(2,'0')}</div><span className="chapter-pill">{story.chapter}</span><h3>{story.prompt}</h3><p>{story.note||'A voice memory saved with love.'}</p><div className="story-footer"><button onClick={()=>playStory(story)} aria-label={`Play ${story.prompt}`}>{playingId===story.id?<Pause/>:<Play fill="currentColor"/>}</button><div><strong>{story.hasAudio?formatTime(story.duration):story.id.startsWith('sample')?'Listen to sample':'Written memory'}</strong><span>{story.date}</span></div>{story.hasAudio&&<button className="icon-quiet" aria-label="Download memory" onClick={async()=>{const b=await recordingLoad(story.id);if(!b)return;const a=document.createElement('a');a.href=URL.createObjectURL(b);a.download=`kyuc-${story.id}.webm`;a.click()}}><Download/></button>}</div></article>)}</div>
      <div className="privacy-note"><LockKeyhole/><div><strong>Your private family space</strong><p>Saved stories and recordings live on this device. Kyuc never uploads them in this prototype.</p></div></div></section>}
    <footer><div className="brand"><span className="brand-mark">K</span><span><strong>Kyuc</strong><small>Memories that move through time</small></span></div><p>Made for the stories only your family can tell.</p><span>Private · Gentle · Yours</span></footer>
  </main>;
}
