<template>
    <Head :title="contact.full_name || contact.email" />

    <AppLayout>
        <!-- Breadcrumb + nav actions -->
        <div class="cd-topbar">
            <div class="cd-topbar-left">
                <Link href="/contacts" class="cd-back-circle-btn" title="Back to Contacts">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" class="back-arrow-icon"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5"/></svg>
                </Link>
                <nav class="cd-breadcrumb">
                    <Link href="/contacts" class="cd-breadcrumb-link">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="cd-breadcrumb-icon">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M2.25 12l8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25" />
                        </svg>
                        <span>Contacts</span>
                    </Link>
                    <span class="cd-breadcrumb__sep">/</span>
                    <span class="cd-breadcrumb__current">{{ contact.full_name || contact.email }}</span>
                </nav>
            </div>
            <div class="cd-nav-actions">
                <button class="btn cd-delete-btn" @click="deleteContact">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="btn-icon"><path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" /></svg>
                    <span>Delete</span>
                </button>
            </div>
        </div>

        <!-- Flash -->
        <div v-if="$page.props.flash?.success" class="flash-success">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="flash-icon"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
            <span>{{ $page.props.flash.success }}</span>
        </div>

        <!-- Detail layout -->
        <div class="contact-detail-layout">

            <!-- Left column -->
            <div class="cd-left">

                <!-- Contact header card -->
                <div class="cd-header">
                    <div class="cd-header-meta">
                        <div class="cd-avatar-lg" :style="{ background: avatarColor(contact.email) }">
                            {{ contact.initials }}
                        </div>
                        <div class="cd-info">
                            <div class="cd-name-row">
                                <span class="cd-name">{{ contact.full_name || contact.email }}</span>
                                <div class="cd-badges">
                                    <!-- Contact type inline select wrapper -->
                                    <div class="cd-badge-select-wrapper">
                                        <select class="cd-badge-type" v-model="typeForm" @change="updateField('contact_type', typeForm)">
                                            <option value="lead">Lead</option>
                                            <option value="prospect">Prospect</option>
                                            <option value="customer">Customer</option>
                                            <option value="partner">Partner</option>
                                        </select>
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="select-chevron"><path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z" clip-rule="evenodd" /></svg>
                                    </div>
                                    <!-- Status inline select wrapper -->
                                    <div class="cd-badge-select-wrapper">
                                        <select class="cd-badge-status" :class="statusBadgeClass(statusForm)" v-model="statusForm" @change="updateField('status', statusForm)">
                                            <option value="subscribed">Subscribed</option>
                                            <option value="unsubscribed">Unsubscribed</option>
                                            <option value="bounced">Bounced</option>
                                            <option value="spam_reported">Spam Reported</option>
                                        </select>
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="select-chevron"><path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z" clip-rule="evenodd" /></svg>
                                    </div>
                                </div>
                            </div>
                            <p class="cd-email-line">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="cd-info-icon"><path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75" /></svg>
                                {{ contact.email }}
                            </p>
                            <p class="cd-added-line">Added {{ formatDate(contact.created_at) }}</p>
                        </div>
                    </div>

                    <!-- Lists & Tags chips -->
                    <div class="cd-lt-area">
                        <div class="cd-lt-section">
                            <div class="cd-lt-label">
                                <span>Lists</span>
                                <div class="cd-lt-add-wrap">
                                    <button class="cd-lt-add" @click.stop="toggleChipDrop('list')" title="Add list">
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" style="width:12px;height:12px"><path d="M10.75 4.75a.75.75 0 00-1.5 0v4.5h-4.5a.75.75 0 000 1.5h4.5v4.5a.75.75 0 001.5 0v-4.5h4.5a.75.75 0 000-1.5h-4.5v-4.5z" /></svg>
                                    </button>
                                    <div class="chip-drop-menu" v-show="chipDrop === 'list'" @click.stop>
                                        <a v-for="l in unassignedLists" :key="l.id" class="chip-drop-item" @click="attachList(l)">{{ l.title }}</a>
                                        <span v-if="!unassignedLists.length" class="chip-drop-item empty-state">All lists assigned</span>
                                    </div>
                                </div>
                            </div>
                            <div class="cd-chips">
                                <span v-for="l in contact.lists" :key="l.id" class="cd-chip cd-chip--list" :style="{ borderColor: l.color || '#4285F4' }">
                                    {{ l.title }}
                                    <button class="cd-chip-remove" @click="detachList(l)">&times;</button>
                                </span>
                                <span v-if="!contact.lists.length" class="cd-chip-empty">None</span>
                            </div>
                        </div>
                        <div class="cd-lt-section">
                            <div class="cd-lt-label">
                                <span>Tags</span>
                                <div class="cd-lt-add-wrap">
                                    <button class="cd-lt-add" @click.stop="toggleChipDrop('tag')" title="Add tag">
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" style="width:12px;height:12px"><path d="M10.75 4.75a.75.75 0 00-1.5 0v4.5h-4.5a.75.75 0 000 1.5h4.5v4.5a.75.75 0 001.5 0v-4.5h4.5a.75.75 0 000-1.5h-4.5v-4.5z" /></svg>
                                    </button>
                                    <div class="chip-drop-menu" v-show="chipDrop === 'tag'" @click.stop>
                                        <a v-for="t in unassignedTags" :key="t.id" class="chip-drop-item" @click="attachTag(t)">{{ t.title }}</a>
                                        <span v-if="!unassignedTags.length" class="chip-drop-item empty-state">All tags assigned</span>
                                    </div>
                                </div>
                            </div>
                            <div class="cd-chips">
                                <span v-for="t in contact.tags" :key="t.id" class="cd-chip cd-chip--tag" :style="{ borderLeftColor: t.color || '#fbbf24' }">
                                    {{ t.title }}
                                    <button class="cd-chip-remove" @click="detachTag(t)">&times;</button>
                                </span>
                                <span v-if="!contact.tags.length" class="cd-chip-empty">None</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Tab nav -->
                <nav class="cd-tabs" role="tablist">
                    <a v-for="tab in tabs" :key="tab.key" href="#" class="cd-tab" :class="{ 'is-active': activeTab === tab.key }"
                        @click.prevent="activeTab = tab.key" role="tab">
                        {{ tab.label }}
                    </a>
                </nav>

                <!-- Overview tab -->
                <div v-show="activeTab === 'overview'" class="cd-tab-panel">
                    <div class="cd-overview-grid">
                        <!-- Basic Info -->
                        <div class="cd-form-section">
                            <h3 class="cd-section-title">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="section-title-icon"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" /></svg>
                                Basic Information
                            </h3>

                            <div class="cd-form-group">
                                <div class="cd-prefix-row">
                                    <div>
                                        <label class="form-label">Prefix</label>
                                        <CwSelect v-model="editForm.prefix" :options="prefixOptions" placeholder="Prefix" />
                                    </div>
                                    <div>
                                        <label class="form-label">First Name</label>
                                        <input type="text" class="form-input" v-model="editForm.first_name" placeholder="John">
                                    </div>
                                    <div>
                                        <label class="form-label">Last Name</label>
                                        <input type="text" class="form-input" v-model="editForm.last_name" placeholder="Doe">
                                    </div>
                                </div>
                            </div>

                            <div class="cd-form-group">
                                <label class="form-label">Email Address</label>
                                <input type="email" class="form-input" v-model="editForm.email" placeholder="example@domain.com">
                            </div>

                            <div class="cd-form-group">
                                <label class="form-label">Phone / Mobile</label>
                                <input type="tel" class="form-input" v-model="editForm.phone" placeholder="+1 (555) 000-0000">
                            </div>

                            <div class="cd-form-group">
                                <label class="form-label">Date of Birth</label>
                                <CwDateTimePicker v-model="editForm.date_of_birth" mode="date" :disable-past="false" placeholder="Select Date of Birth" />
                            </div>
                        </div>

                        <!-- Address Info -->
                        <div class="cd-form-section">
                            <h3 class="cd-section-title">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="section-title-icon"><path stroke-linecap="round" stroke-linejoin="round" d="M15 10.5a3 3 0 11-6 0 3 3 0 016 0z" /><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25s-7.5-4.108-7.5-11.25a7.5 7.5 0 1115 0z" /></svg>
                                Address Information
                            </h3>

                            <div class="cd-form-group">
                                <label class="form-label">Address Line 1</label>
                                <input type="text" class="form-input" v-model="editForm.address_line_1" placeholder="123 Main St">
                            </div>

                            <div class="cd-form-group">
                                <label class="form-label">Address Line 2</label>
                                <input type="text" class="form-input" v-model="editForm.address_line_2" placeholder="Apt, Suite, Floor">
                            </div>

                            <div class="cd-form-group">
                                <div class="cd-addr-2col">
                                    <div>
                                        <label class="form-label">City</label>
                                        <input type="text" class="form-input" v-model="editForm.city" placeholder="New York">
                                    </div>
                                    <div>
                                        <label class="form-label">State</label>
                                        <input type="text" class="form-input" v-model="editForm.state" placeholder="NY">
                                    </div>
                                </div>
                            </div>

                            <div class="cd-form-group">
                                <div class="cd-addr-2col">
                                    <div>
                                        <label class="form-label">ZIP Code</label>
                                        <input type="text" class="form-input" v-model="editForm.postal_code" placeholder="10001">
                                    </div>
                                    <div>
                                        <label class="form-label">Country</label>
                                        <input type="text" class="form-input" v-model="editForm.country" placeholder="United States">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="cd-update-row">
                        <button class="btn btn-primary btn-save" @click="saveContact" :disabled="saving">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.2" stroke="currentColor" class="btn-icon" v-if="!saving"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" /></svg>
                            <span>{{ saving ? 'Saving…' : 'Update Contact' }}</span>
                        </button>
                    </div>
                </div>

                <!-- Emails tab -->
                <div v-show="activeTab === 'emails'" class="cd-tab-panel">
                    <div class="cd-empty-tab-state">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="empty-state-icon"><path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75" /></svg>
                        <p>No email history yet.</p>
                    </div>
                </div>

                <!-- Form Submissions tab -->
                <div v-show="activeTab === 'forms'" class="cd-tab-panel">
                    <div class="cd-empty-tab-state">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="empty-state-icon"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" /></svg>
                        <p>No form submissions yet.</p>
                    </div>
                </div>

                <!-- Notes & Activities tab -->
                <div v-show="activeTab === 'notes'" class="cd-tab-panel">
                    <!-- Add note -->
                    <div class="cd-note-input-container">
                        <textarea class="form-textarea cd-note-textarea" v-model="noteText" placeholder="Write a note about this contact..." rows="3"></textarea>
                        <div class="cd-note-submit-bar">
                            <button class="btn btn-primary btn-sm btn-add-note" @click="addNote" :disabled="!noteText.trim()">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="btn-icon"><path d="M10.75 4.75a.75.75 0 00-1.5 0v4.5h-4.5a.75.75 0 000 1.5h4.5v4.5a.75.75 0 001.5 0v-4.5h4.5a.75.75 0 000-1.5h-4.5v-4.5z" /></svg>
                                <span>Add Note</span>
                            </button>
                        </div>
                    </div>

                    <!-- Note cards -->
                    <div class="cd-notes-section">
                        <h4 class="cd-subsection-title">Notes History</h4>
                        <div class="cd-notes-list">
                            <div v-for="note in contact.notes" :key="note.id" class="cd-note-card">
                                <div class="cd-note-card-body">
                                    <p class="cd-note-content">{{ note.content }}</p>
                                    <button class="note-delete-btn" @click="deleteNote(note)" title="Delete note">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:14px;height:14px"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /></svg>
                                    </button>
                                </div>
                                <div class="cd-note-meta">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" style="width:12px;height:12px;color:#9ca3af"><path d="M10 8a3 3 0 100-6 3 3 0 000 6zM3.465 14.493a1.23 1.23 0 00.41 1.412A9.957 9.957 0 0010 18c2.31 0 4.438-.784 6.131-2.1.29-.226.395-.615.222-.924-.492-.879-1.47-1.5-2.753-1.5h-7.2c-1.28 0-2.261.621-2.753 1.5z" /></svg>
                                    <span>{{ note.created_by || 'Workspace Owner' }}</span>
                                    <span class="meta-dot">·</span>
                                    <span>{{ formatDate(note.created_at) }}</span>
                                </div>
                            </div>
                            <p v-if="!contact.notes.length" class="cd-notes-empty-state">No notes added to this contact yet.</p>
                        </div>
                    </div>

                    <!-- Activity log -->
                    <div class="cd-activity-list" v-if="contact.activities.length">
                        <p class="cd-activity-label">Activity Log</p>
                        <div class="cd-activity-timeline">
                            <div v-for="act in contact.activities" :key="act.id" class="cd-activity-item">
                                <div class="cd-activity-dot-wrapper">
                                    <span class="cd-activity-dot" :class="activityDotClass(act.type)"></span>
                                </div>
                                <div class="cd-activity-content">
                                    <p class="cd-activity-desc">{{ act.description }}</p>
                                    <p class="cd-activity-date">{{ formatDateTime(act.occurred_at) }}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
            <!-- /cd-left -->

            <!-- Aside -->
            <aside class="cd-aside">
                <div class="cd-aside-header">
                    <h4 class="cd-aside-title">Contact Profile Info</h4>
                </div>
                <div class="cd-aside-body">
                    <div class="cd-aside-item">
                        <span class="cd-aside-label">Status</span>
                        <span class="badge" :class="statusClass(contact.status)">{{ contact.status }}</span>
                    </div>
                    <div class="cd-aside-item">
                        <span class="cd-aside-label">Type</span>
                        <span class="cd-aside-val text-capitalize">{{ contact.contact_type }}</span>
                    </div>
                    <div class="cd-aside-item">
                        <span class="cd-aside-label">Source</span>
                        <span class="cd-aside-val">{{ contact.source || 'Direct' }}</span>
                    </div>
                    <div class="cd-aside-item">
                        <span class="cd-aside-label">Total Points</span>
                        <span class="cd-aside-badge-points">{{ contact.total_points }} pts</span>
                    </div>
                    <div class="cd-aside-item">
                        <span class="cd-aside-label">Lifetime Value</span>
                        <span class="cd-aside-val-highlight">${{ contact.life_time_value }}</span>
                    </div>
                    <div class="cd-aside-item">
                        <span class="cd-aside-label">Last Activity</span>
                        <span class="cd-aside-val">{{ contact.last_activity ? formatDate(contact.last_activity) : '-' }}</span>
                    </div>
                    <div class="cd-aside-item">
                        <span class="cd-aside-label">Created</span>
                        <span class="cd-aside-val">{{ formatDate(contact.created_at) }}</span>
                    </div>
                </div>
            </aside>

        </div>
    </AppLayout>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount, watch } from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import CwSelect from '@/Components/CwSelect.vue';
import CwDateTimePicker from '@/Components/CwDateTimePicker.vue';
import { useTenantTimezone } from '@/Composables/useTenantTimezone';

const props = defineProps({
    contact:  Object,
    allLists: Array,
    allTags:  Array,
});

const activeTab  = ref('overview');
const saving     = ref(false);
const noteText   = ref('');
const chipDrop   = ref(null);

const tabs = [
    { key: 'overview', label: 'Overview' },
    { key: 'emails',   label: 'Emails' },
    { key: 'forms',    label: 'Form Submissions' },
    { key: 'notes',    label: 'Notes & Activities' },
];

const typeForm   = ref(props.contact.contact_type || 'lead');
const statusForm = ref(props.contact.status       || 'subscribed');

const editForm = reactive({
    prefix:          props.contact.prefix          || '',
    first_name:      props.contact.first_name      || '',
    last_name:       props.contact.last_name       || '',
    email:           props.contact.email           || '',
    phone:           props.contact.phone           || '',
    date_of_birth:   props.contact.date_of_birth ? props.contact.date_of_birth.substring(0, 10) : '',
    address_line_1:  props.contact.address_line_1  || '',
    address_line_2:  props.contact.address_line_2  || '',
    city:            props.contact.city            || '',
    state:           props.contact.state           || '',
    postal_code:     props.contact.postal_code     || '',
    country:         props.contact.country         || '',
});

const prefixOptions = [
    { value: '', label: 'None' },
    { value: 'Mr.', label: 'Mr.' },
    { value: 'Mrs.', label: 'Mrs.' },
    { value: 'Ms.', label: 'Ms.' },
    { value: 'Dr.', label: 'Dr.' },
    { value: 'Prof.', label: 'Prof.' }
];

watch(() => props.contact, (newContact) => {
    if (newContact) {
        editForm.prefix = newContact.prefix || '';
        editForm.first_name = newContact.first_name || '';
        editForm.last_name = newContact.last_name || '';
        editForm.email = newContact.email || '';
        editForm.phone = newContact.phone || '';
        editForm.date_of_birth = newContact.date_of_birth ? newContact.date_of_birth.substring(0, 10) : '';
        editForm.address_line_1 = newContact.address_line_1 || '';
        editForm.address_line_2 = newContact.address_line_2 || '';
        editForm.city = newContact.city || '';
        editForm.state = newContact.state || '';
        editForm.postal_code = newContact.postal_code || '';
        editForm.country = newContact.country || '';
        typeForm.value = newContact.contact_type || 'lead';
        statusForm.value = newContact.status || 'subscribed';
    }
}, { deep: true });

// Lists / Tags
const unassignedLists = computed(() => {
    const ids = (props.contact.lists || []).map(l => l.id);
    return props.allLists.filter(l => !ids.includes(l.id));
});

const unassignedTags = computed(() => {
    const ids = (props.contact.tags || []).map(t => t.id);
    return props.allTags.filter(t => !ids.includes(t.id));
});

function toggleChipDrop(name) {
    chipDrop.value = chipDrop.value === name ? null : name;
}

function closeChipDrops() { chipDrop.value = null; }

onMounted(() => document.addEventListener('click', closeChipDrops));
onBeforeUnmount(() => document.removeEventListener('click', closeChipDrops));

function attachList(list) {
    chipDrop.value = null;
    router.post(route('contacts.lists.attach', { contact: props.contact.id, list: list.id }), {}, { preserveScroll: true });
}

async function detachList(list) {
    if (!await confirm(`Remove from list "${list.title}"?`)) return;
    router.delete(route('contacts.lists.detach', { contact: props.contact.id, list: list.id }), { preserveScroll: true });
}

function attachTag(tag) {
    chipDrop.value = null;
    router.post(route('contacts.tags.attach', { contact: props.contact.id, tag: tag.id }), {}, { preserveScroll: true });
}

async function detachTag(tag) {
    if (!await confirm(`Remove tag "${tag.title}"?`)) return;
    router.delete(route('contacts.tags.detach', { contact: props.contact.id, tag: tag.id }), { preserveScroll: true });
}

function updateField(field, value) {
    router.patch(route('contacts.update', props.contact.id), { [field]: value }, { preserveScroll: true });
}

function saveContact() {
    saving.value = true;
    // Format date string correctly if datetime is sent
    const dob = editForm.date_of_birth && editForm.date_of_birth.includes('T') 
        ? editForm.date_of_birth.split('T')[0] 
        : editForm.date_of_birth;
    
    router.put(route('contacts.update', props.contact.id), { ...editForm, date_of_birth: dob }, {
        preserveScroll: true,
        onFinish: () => { saving.value = false; },
    });
}

async function deleteContact() {
    if (!await confirm(`Delete "${props.contact.full_name || props.contact.email}"? This cannot be undone.`)) return;
    router.delete(route('contacts.destroy', props.contact.id));
}

function addNote() {
    if (!noteText.value.trim()) return;
    router.post(route('contacts.notes.store', props.contact.id), { content: noteText.value }, {
        preserveScroll: true,
        onSuccess: () => { noteText.value = ''; },
    });
}

async function deleteNote(note) {
    if (!await confirm('Delete this note?')) return;
    router.delete(route('contacts.notes.destroy', { contact: props.contact.id, note: note.id }), { preserveScroll: true });
}

// Helpers
const avatarColors = ['#7c3aed','#0891b2','#dc2626','#059669','#d97706','#6366f1','#4285F4','#EA4335'];

function avatarColor(email) {
    let h = 0;
    for (let i = 0; i < email.length; i++) h = email.charCodeAt(i) + ((h << 5) - h);
    return avatarColors[Math.abs(h) % avatarColors.length];
}

function statusClass(s) {
    return { 
        subscribed: 'badge--subscribed', 
        unsubscribed: 'badge--unsubscribed', 
        bounced: 'badge--bounced', 
        spam_reported: 'badge--bounced' 
    }[s] || '';
}

function statusBadgeClass(s) {
    return {
        subscribed: 'status--subscribed',
        unsubscribed: 'status--unsubscribed',
        bounced: 'status--bounced',
        spam_reported: 'status--bounced'
    }[s] || '';
}

function activityDotClass(type) {
    return {
        created:        'cd-activity-dot--green',
        updated:        'cd-activity-dot--blue',
        note_added:     'cd-activity-dot--blue',
        list_added:     'cd-activity-dot--green',
        list_removed:   'cd-activity-dot--gray',
        tag_added:      'cd-activity-dot--green',
        tag_removed:    'cd-activity-dot--gray',
        imported:       'cd-activity-dot--gray',
        email_sent:     'cd-activity-dot--blue',
        email_opened:   'cd-activity-dot--green',
        email_clicked:  'cd-activity-dot--purple',
        conversion:     'cd-activity-dot--green',
        unsubscribed:   'cd-activity-dot--red',
        status_changed: 'cd-activity-dot--red',
    }[type] || '';
}

const { formatDate: formatDateTz, formatDateTime: formatDateTimeTz } = useTenantTimezone();

function formatDate(iso) {
    if (!iso) return '-';
    return formatDateTz(iso);
}

function formatDateTime(iso) {
    if (!iso) return '-';
    return formatDateTimeTz(iso);
}
</script>

<style scoped>
/* Page Layout */
.cd-topbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    flex-wrap: wrap;
    gap: 12px;
}

.cd-breadcrumb {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
}

.cd-breadcrumb-link {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    color: var(--text-secondary);
    text-decoration: none;
    transition: color 0.2s ease;
    font-weight: 500;
}

.cd-breadcrumb-link:hover {
    color: var(--active-text);
}

.cd-breadcrumb-icon {
    width: 16px;
    height: 16px;
}

.cd-breadcrumb__sep {
    color: var(--text-muted);
}

.cd-breadcrumb__current {
    color: var(--text-primary);
    font-weight: 600;
}

.cd-nav-actions {
    display: flex;
    align-items: center;
    gap: 12px;
}

/* Base Layout */
.contact-detail-layout {
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 24px;
    align-items: start;
}

@media (max-width: 1024px) {
    .contact-detail-layout {
        grid-template-columns: 1fr;
    }
}

.cd-left {
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 24px;
}

/* Header Profile Card */
.cd-header {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 28px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.cd-header-meta {
    display: flex;
    gap: 20px;
    margin-bottom: 24px;
    align-items: center;
}

@media (max-width: 640px) {
    .cd-header-meta {
        flex-direction: column;
        text-align: center;
    }
}

.cd-avatar-lg {
    width: 76px;
    height: 76px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    font-weight: 700;
    color: #fff;
    flex-shrink: 0;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}

.cd-info {
    flex: 1;
    min-width: 0;
}

.cd-name-row {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
    margin-bottom: 6px;
}

@media (max-width: 640px) {
    .cd-name-row {
        justify-content: center;
    }
}

.cd-name {
    font-size: 20px;
    font-weight: 700;
    color: var(--text-primary);
    letter-spacing: -0.02em;
}

.cd-badges {
    display: flex;
    align-items: center;
    gap: 8px;
}

/* Badge Select Box Wrapper */
.cd-badge-select-wrapper {
    position: relative;
    display: inline-flex;
    align-items: center;
}

.cd-badge-type, .cd-badge-status {
    padding: 4px 28px 4px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    cursor: pointer;
    appearance: none;
    -webkit-appearance: none;
    border: 1px solid var(--border-color);
    transition: all 0.2s ease;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.cd-badge-type {
    background: var(--bg-hover);
    color: var(--text-secondary);
}

.cd-badge-type:hover {
    background: var(--bg-hover-strong);
    border-color: var(--text-muted);
}

.cd-badge-status {
    background: rgba(16, 185, 129, 0.1);
    color: rgb(16, 185, 129);
    border-color: rgba(16, 185, 129, 0.2);
}

.cd-badge-status.status--subscribed {
    background: rgba(16, 185, 129, 0.1);
    color: rgb(5, 150, 105);
    border-color: rgba(16, 185, 129, 0.2);
}

.cd-badge-status.status--unsubscribed {
    background: rgba(245, 158, 11, 0.1);
    color: rgb(217, 119, 6);
    border-color: rgba(245, 158, 11, 0.2);
}

.cd-badge-status.status--bounced {
    background: rgba(239, 68, 68, 0.1);
    color: rgb(220, 38, 38);
    border-color: rgba(239, 68, 68, 0.2);
}

.cd-badge-status:hover {
    filter: brightness(0.95);
}

.select-chevron {
    position: absolute;
    right: 8px;
    width: 12px;
    height: 12px;
    color: var(--text-muted);
    pointer-events: none;
}

.cd-email-line {
    font-size: 13.5px;
    color: var(--text-secondary);
    margin: 0 0 6px;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.cd-info-icon {
    width: 14px;
    height: 14px;
    color: var(--text-muted);
}

.cd-added-line {
    font-size: 12px;
    color: var(--text-muted);
    margin: 0;
}

/* Lists/Tags Chips Area */
.cd-lt-area {
    display: flex;
    gap: 28px;
    flex-wrap: wrap;
    padding-top: 20px;
    border-top: 1px solid var(--border-color);
}

.cd-lt-section {
    flex: 1;
    min-width: 200px;
}

.cd-lt-label {
    font-size: 11px;
    font-weight: 700;
    color: var(--text-muted);
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    text-transform: uppercase;
    letter-spacing: .08em;
}

.cd-lt-add-wrap {
    position: relative;
}

.cd-lt-add {
    width: 22px;
    height: 22px;
    border-radius: 50%;
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--text-secondary);
    transition: all 0.2s ease;
}

.cd-lt-add:hover {
    background: var(--bg-hover-strong);
    color: var(--text-primary);
    transform: scale(1.05);
}

.chip-drop-menu {
    position: absolute;
    top: calc(100% + 6px);
    right: 0;
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    z-index: 50;
    min-width: 180px;
    padding: 6px 0;
}

.chip-drop-item {
    display: block;
    padding: 8px 14px;
    font-size: 12.5px;
    color: var(--text-secondary);
    cursor: pointer;
    text-decoration: none;
    transition: background 0.15s ease, color 0.15s ease;
}

.chip-drop-item:hover {
    background: var(--bg-hover);
    color: var(--text-primary);
}

.chip-drop-item.empty-state {
    color: var(--text-muted);
    cursor: default;
    font-style: italic;
}

.chip-drop-item.empty-state:hover {
    background: transparent;
}

.cd-chips {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
}

.cd-chip {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    font-weight: 500;
    color: var(--text-primary);
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    border-radius: 6px;
    padding: 4px 8px;
    transition: all 0.15s ease;
}

.cd-chip:hover {
    background: var(--bg-hover-strong);
}

.cd-chip--tag {
    border-left-color: #fbbf24;
    background: rgba(251, 191, 36, 0.05);
}

.cd-chip-remove {
    background: none;
    border: none;
    cursor: pointer;
    color: var(--text-muted);
    font-size: 14px;
    line-height: 1;
    padding: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.cd-chip-remove:hover {
    color: #ef4444;
}

.cd-chip-empty {
    font-size: 12px;
    color: var(--text-muted);
    font-style: italic;
}

/* Tabs Navigation */
.cd-tabs {
    display: flex;
    border-bottom: 1px solid var(--border-color);
    background: var(--bg-surface);
    border-radius: 12px 12px 0 0;
    padding: 0 16px;
    margin-bottom: -1px;
    overflow-x: auto;
}

.cd-tab {
    padding: 16px 20px;
    font-size: 13.5px;
    font-weight: 600;
    color: var(--text-secondary);
    text-decoration: none;
    border-bottom: 3px solid transparent;
    transition: all 0.2s ease;
    white-space: nowrap;
}

.cd-tab.is-active {
    color: var(--active-text);
    border-bottom-color: var(--active-text);
}

.cd-tab:hover:not(.is-active) {
    color: var(--text-primary);
    border-bottom-color: var(--border-color);
}

/* Tab Panels */
.cd-tab-panel {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 0 0 12px 12px;
    padding: 28px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.cd-overview-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 32px;
}

@media (max-width: 768px) {
    .cd-overview-grid {
        grid-template-columns: 1fr;
    }
}

.cd-form-section {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.cd-section-title {
    font-size: 13px;
    font-weight: 700;
    color: var(--active-text);
    text-transform: uppercase;
    letter-spacing: .08em;
    margin: 0 0 8px;
    padding-bottom: 10px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 8px;
}

.section-title-icon {
    width: 16px;
    height: 16px;
    color: var(--active-text);
}

.cd-form-group {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.cd-prefix-row {
    display: grid;
    grid-template-columns: 110px 1fr 1fr;
    gap: 12px;
}

@media (max-width: 480px) {
    .cd-prefix-row {
        grid-template-columns: 1fr;
    }
}

.cd-addr-2col {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
}

.cd-update-row {
    margin-top: 28px;
    padding-top: 20px;
    border-top: 1px solid var(--border-color);
    display: flex;
    justify-content: flex-end;
}

.btn-save {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 20px;
    font-weight: 600;
}

/* Empty Tab State */
.cd-empty-tab-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 0;
    color: var(--text-muted);
    gap: 12px;
}

.empty-state-icon {
    width: 48px;
    height: 48px;
    color: var(--border-color);
}

.cd-empty-tab-state p {
    font-size: 14px;
    font-weight: 500;
}

/* Notes & Activities Tab */
.cd-note-input-container {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 24px;
    box-shadow: 0 1px 2px rgba(0,0,0,0.02);
}

.cd-note-textarea {
    width: 100%;
    border: none !important;
    padding: 0;
    resize: vertical;
    font-size: 13.5px;
    color: var(--text-primary);
    background: transparent;
}

.cd-note-textarea:focus {
    box-shadow: none !important;
    outline: none !important;
}

.cd-note-submit-bar {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px solid var(--border-color);
}

.btn-add-note {
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.cd-notes-section {
    margin-bottom: 28px;
}

.cd-subsection-title {
    font-size: 12px;
    font-weight: 700;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: 0.05em;
    margin: 0 0 12px;
}

.cd-notes-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.cd-note-card {
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 16px;
    transition: all 0.2s ease;
}

.cd-note-card:hover {
    border-color: var(--text-muted);
}

.cd-note-card-body {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 12px;
}

.cd-note-content {
    font-size: 13px;
    color: var(--text-primary);
    margin: 0;
    line-height: 1.5;
    white-space: pre-line;
}

.note-delete-btn {
    background: none;
    border: none;
    cursor: pointer;
    color: var(--text-muted);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 4px;
    border-radius: 4px;
    transition: all 0.15s ease;
}

.note-delete-btn:hover {
    color: #ef4444;
    background: rgba(239, 68, 68, 0.05);
}

.cd-note-meta {
    font-size: 11px;
    color: var(--text-muted);
    margin-top: 10px;
    display: flex;
    align-items: center;
    gap: 6px;
    font-weight: 500;
}

.meta-dot {
    color: var(--border-color);
}

.cd-notes-empty-state {
    color: var(--text-muted);
    font-size: 13px;
    text-align: center;
    padding: 24px 0;
    font-style: italic;
}

/* Activity Log Timeline */
.cd-activity-list {
    margin-top: 24px;
    padding-top: 24px;
    border-top: 1px solid var(--border-color);
}

.cd-activity-label {
    font-size: 12px;
    font-weight: 700;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: .08em;
    margin: 0 0 16px;
}

.cd-activity-timeline {
    position: relative;
    padding-left: 20px;
}

.cd-activity-timeline::before {
    content: '';
    position: absolute;
    top: 6px;
    bottom: 6px;
    left: 4px;
    width: 2px;
    background: var(--border-color);
}

.cd-activity-item {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
    position: relative;
}

.cd-activity-item:last-child {
    margin-bottom: 0;
}

.cd-activity-dot-wrapper {
    position: absolute;
    left: -20px;
    width: 10px;
    height: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.cd-activity-dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: #d1d5db;
    border: 2px solid var(--bg-surface);
    box-shadow: 0 0 0 2px var(--bg-surface);
}

.cd-activity-dot--green  { background: #10b981; }
.cd-activity-dot--blue   { background: #3b82f6; }
.cd-activity-dot--gray   { background: #9ca3af; }
.cd-activity-dot--red    { background: #ef4444; }
.cd-activity-dot--purple { background: #8b5cf6; }

.cd-activity-content {
    flex: 1;
    min-width: 0;
}

.cd-activity-desc {
    font-size: 13px;
    color: var(--text-primary);
    margin: 0;
    font-weight: 500;
}

.cd-activity-date {
    font-size: 11px;
    color: var(--text-muted);
    margin: 4px 0 0;
}

/* Sidebar Info Card */
.cd-aside {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.cd-aside-header {
    padding: 16px 20px;
    border-bottom: 1px solid var(--border-color);
    background: var(--bg-hover);
}

.cd-aside-title {
    font-size: 13px;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.cd-aside-body {
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 14px;
}

.cd-aside-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12.5px;
    gap: 12px;
}

.cd-aside-label {
    color: var(--text-muted);
    font-weight: 500;
}

.cd-aside-val {
    color: var(--text-primary);
    font-weight: 600;
    text-align: right;
}

.cd-aside-val-highlight {
    color: #10b981;
    font-weight: 700;
    font-size: 13.5px;
}

.cd-aside-badge-points {
    background: rgba(59, 130, 246, 0.1);
    color: #3b82f6;
    font-weight: 700;
    font-size: 11.5px;
    padding: 2px 8px;
    border-radius: 12px;
}

.text-capitalize {
    text-transform: capitalize;
}

/* Flash notifications */
.flash-success {
    background: #ecfdf5;
    border: 1px solid #a7f3d0;
    color: #065f46;
    border-radius: 8px;
    padding: 12px 16px;
    font-size: 13.5px;
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 500;
}

.flash-icon {
    width: 18px;
    height: 18px;
    color: #10b981;
}

/* Premium Navigation Buttons styling */
.cd-topbar-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.cd-back-circle-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    border: 1px solid var(--border-color);
    background-color: var(--bg-surface);
    color: var(--text-secondary);
    transition: all 0.2s ease;
    cursor: pointer;
}

.cd-back-circle-btn:hover {
    border-color: var(--text-muted);
    background-color: var(--bg-hover);
    color: var(--text-primary);
    transform: translateX(-2px);
}

.back-arrow-icon {
    width: 14px;
    height: 14px;
    transition: transform 0.2s ease;
}

.cd-delete-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    border-radius: 20px !important;
    padding: 8px 16px !important;
    font-weight: 600;
    font-size: 12.5px;
    transition: all 0.2s ease;
}

.cd-delete-btn {
    border-color: #fca5a5 !important;
    color: #dc2626 !important;
    background-color: var(--bg-surface) !important;
}

.cd-delete-btn:hover {
    border-color: #dc2626 !important;
    background-color: #fef2f2 !important;
    color: #991b1b !important;
}

.btn-icon {
    width: 14px;
    height: 14px;
}
</style>

