// Customer home reads the same protected records as the shared workspace.
function customerHomeKind(r){return r.kind==='order'?'Product order':r.kind==='stay'?'Stay':r.kind==='appointment'?'Appointment':r.calendar_kind==='tour'?'Tour':r.calendar_kind==='track'?'Track session':'Group session';}
function customerHomeStatus(r){return {preparing:'Preparing',ready:'Ready to collect',collected:'Collected',pending:'Awaiting confirmation',confirmed:'Confirmed',completed:'Completed',held:'Temporary hold',cancelled:'Cancelled',expired:'Expired',no_show:'No show',checked_in:'Checked in'}[r.status]||r.status;}
function customerHomeDate(r){
  if(!r.schedule)return '';
  const s=r.schedule,f=window.BOOKUNO_REGION.dateFormatter({timeZone:s.timezone,dateStyle:'medium',...(r.kind==='stay'?{}:{timeStyle:'short'})});
  return f.format(new Date(s.starts_at))+' → '+f.format(new Date(s.ends_at));
}
const CUSTOMER_BUSINESS_CATEGORIES=[['barbershop','Barber'],['hair_salon','Hair & Beauty'],['nail_salon','Nails'],['massage_spa','Wellness'],['personal_trainer','Fitness'],['cleaner','Cleaning'],['tradesperson','Trades'],['campsite','Stays & Camp'],['rental','Hire & Rental'],['event','Events'],['general_service','Other businesses']];
function customerHomeCategoryLabel(type){if(['general_service','general','other'].includes(type))return '';const label=typeof bizTypeLabel==='function'?bizTypeLabel(type):type;return typeof label==='string'?label.replaceAll('_',' ').replace(/^./,x=>x.toUpperCase()):'';}
function customerHomeBusinessMeta(b){return [customerHomeCategoryLabel(b.type),b.address?.city||b.address?.region].filter(Boolean).join(' · ');}
function FrameCustomerHome({logoVariant='default'}){
  const [personal,setPersonal]=React.useState({loading:true,name:'',records:[],error:'',actor:null});
  const [directory,setDirectory]=React.useState({loading:true,rows:[],error:''});
  const [revision,setRevision]=React.useState(0),[query,setQuery]=React.useState(''),[place,setPlace]=React.useState('');
  const generation=React.useRef(0);
  React.useEffect(()=>{
    let live=true;const token=++generation.current,api=window.BOOKUNO_API;
    const current=()=>live&&token===generation.current;
    setPersonal({loading:true,name:'',records:[],error:'',actor:null});setDirectory({loading:true,rows:[],error:''});
    async function loadPersonal(){try{
      const session=await api.getSession(),user=session?.user;
      if(!user?.id)throw Error('Sign in to view your orders and bookings.');
      const result=await api.listMyOrders(0);
      window.BOOKUNO_ORDERS.snapshot(result,null,user.id,0,true);
      const after=await api.getSession();if(after?.user?.id!==user.id)throw Error('Your account changed. Sign in again.');
      if(current())setPersonal({loading:false,name:(user.user_metadata?.full_name||user.user_metadata?.name||'').split(' ')[0],records:result.records.slice(0,3),error:'',actor:user.id});
    }catch(e){if(current())setPersonal({loading:false,name:'',records:[],error:e.message||'Your orders are unavailable. Please try again.',actor:null});}}
    async function loadDirectory(){try{
      const rows=await api.listPublicBusinesses('','');
      if(!Array.isArray(rows)||rows.some(b=>!window.BOOKUNO_ORDERS.uuid(b.id)||typeof b.name!=='string'||typeof b.slug!=='string'))throw Error('Business details could not be verified.');
      if(current())setDirectory({loading:false,rows:rows.slice(0,4),error:''});
    }catch(e){if(current())setDirectory({loading:false,rows:[],error:'Businesses could not be loaded. Please try again.'});}}
    const changed=()=>{generation.current++;setPersonal({loading:true,name:'',records:[],error:'',actor:null});setQuery('');setPlace('');setRevision(n=>n+1);};
    const subscription=api?.onAuthStateChange?.(event=>{if(['SIGNED_IN','SIGNED_OUT','USER_UPDATED','PASSWORD_RECOVERY'].includes(event))changed();});
    window.addEventListener('bookuno-auth-changed',changed);loadPersonal();loadDirectory();
    return()=>{live=false;generation.current++;subscription?.data?.subscription?.unsubscribe?.();window.removeEventListener('bookuno-auth-changed',changed);};
  },[revision]);
  function search(e){e.preventDefault();const params=new URLSearchParams();if(query.trim())params.set('q',query.trim());if(place.trim())params.set('loc',place.trim());window.location.hash='#/search'+(params.size?'?'+params.toString():'');}
  const hour=new Date().getHours(),greeting=hour<12?'Good morning':hour<18?'Good afternoon':'Good evening';
  return <div className="web customer-home">
    <TopNav active="discover" logoVariant={logoVariant} loggedIn/>
    <main id="customer-home-main">
      <section className="ch-hero ch-wrap" aria-labelledby="customer-home-title">
        <p className="ch-eyebrow">{uiText("Your Bookuno")}</p><h1 id="customer-home-title">{uiText(greeting)}{personal.name?', '+personal.name:''}.</h1>
        <p>{uiText("Plans, purchases and a little more possibility.")}</p>
        <div className="ch-hero-actions"><a className="ch-primary" href="/order.html">{uiText("Your orders & bookings ")}<span aria-hidden="true">→</span></a><a className="ch-secondary" href="/app.html#/account">{uiText("Your account")}</a></div>
        <form className="ch-search" onSubmit={search} aria-label={uiText("Find a business")}><label htmlFor="ch-query">{uiText("What are you looking for?")}<input id="ch-query" type="search" value={query} onChange={e=>setQuery(e.target.value)} placeholder={uiText("Business name")}/></label><label htmlFor="ch-place">{uiText("Where?")}<input id="ch-place" value={place} onChange={e=>setPlace(e.target.value)} placeholder={uiText("Town, city or postcode")}/></label><button type="submit">{uiText("Search businesses ")}<span aria-hidden="true">→</span></button></form>
        <p className="ch-help">{uiText("Availability, prices and change rules are set by each business.")}</p>
      </section>
      <section className="ch-section ch-wrap" aria-labelledby="ch-recent-title">
        <div className="ch-section-heading"><div><p className="ch-eyebrow">{uiText("Saved to your account")}</p><h2 id="ch-recent-title">{uiText("Recent orders & bookings")}</h2></div><a href="/order.html">{uiText("View all ")}<span aria-hidden="true">→</span></a></div>
        <p className="ch-section-note">{uiText("Your most recently created records. Open one for its dates, items and recorded balance.")}</p>
        {personal.loading?<p role="status" className="ch-notice">{uiText("Loading your orders and bookings…")}</p>:personal.error?<div role="alert" className="ch-notice ch-error"><p>{uiText(personal.error)}</p><button type="button" onClick={()=>setRevision(n=>n+1)}>{uiText("Try again")}</button><a href="/app.html#/auth">{uiText("Sign in")}</a></div>:!personal.records.length?<div className="ch-notice"><h3>{uiText("A little room for something new.")}</h3><p>{uiText("Your orders and bookings will appear here when they’re connected to your account.")}</p></div>:<div className="ch-record-grid">{personal.records.map(r=><a className="ch-record" key={r.key} href={'/'+window.BOOKUNO_ORDERS.customerUrl(r)}>
          <div className="ch-record-top"><span>{customerHomeKind(r)}</span><span className={'ch-status'+(['cancelled','expired'].includes(r.status)?' ch-status-muted':'')}>{customerHomeStatus(r)}</span></div><h3>{r.title}</h3><p>{r.business_name}</p>{r.schedule&&<p className="ch-record-date">{customerHomeDate(r)}<span>{r.schedule.timezone}</span></p>}<div className="ch-record-bottom"><span>{window.BOOKUNO_ORDERS.money(r.total_cents,r.currency)}<small>{uiText("Saved total")}</small></span><span>{uiText("View details ")}<span aria-hidden="true">→</span></span></div>
        </a>)}</div>}
      </section>
      <section className="ch-directory" aria-labelledby="ch-directory-title"><div className="ch-wrap">
        <div className="ch-section-heading"><div><p className="ch-eyebrow">{uiText("On Bookuno")}</p><h2 id="ch-directory-title">{uiText("Discover businesses")}</h2></div><a href="/app.html#/search">{uiText("Explore all ")}<span aria-hidden="true">→</span></a></div><p className="ch-section-note">{uiText("Open a business to see what it offers and how to get in touch.")}</p>
        {directory.loading?<p role="status" className="ch-notice">{uiText("Loading businesses…")}</p>:directory.error?<div className="ch-notice ch-error" role="alert"><p>{uiText(directory.error)}</p><button type="button" onClick={()=>setRevision(n=>n+1)}>{uiText("Retry businesses")}</button></div>:!directory.rows.length?<p className="ch-notice">{uiText("No published businesses are available here yet. Try searching by name or location.")}</p>:<div className="ch-business-grid">{directory.rows.map(b=><a className="ch-business" key={b.id} href={'/app.html#/b/'+encodeURIComponent(b.slug)}><span className="ch-business-mark" aria-hidden="true">{b.name.trim().slice(0,1).toUpperCase()}</span><div><h3>{b.name}</h3><p>{customerHomeBusinessMeta(b)}</p></div><span className="ch-business-link">{uiText("View business ")}<span aria-hidden="true">↗</span></span></a>)}</div>}
      </div></section>
      <section className="ch-business-cta ch-wrap"><div><p className="ch-eyebrow">{uiText("For your business")}</p><h2>{uiText("A clearer way to run your day.")}</h2><p>{uiText("Bring products, bookings and customers together. Choose the tools that suit the way you work.")}</p></div><a className="ch-secondary" href="/app.html#/business">{uiText("Explore Bookuno for business ")}<span aria-hidden="true">→</span></a></section>
    </main><Footer logoVariant={logoVariant}/>
  </div>;
}
